LeetCode 动态规划 题目分类汇总

LeetCode解题链接

LeetCode 二叉树 题目分类汇总
干货!LeetCode 题解汇总

62. Unique Paths

A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below).

The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below).

How many possible unique paths are there?

Above is a 3 x 7 grid. How many possible unique paths are there?

Note: m and n will be at most 100.

思路

定义一个 m * n 的矩阵 dp,其中dp[m-1][n-1]代表从出发点(0, 0)→点(m, n)的路径个数。

  • dp[i][0] = 1 (i∈[0, m))
  • dp[0][j] = 1 (j∈[0, n))
  • dp[m][n] = dp[m][n-1] + dp[m-1][n] (m > 0, n > 0)

优化

  1. 在使用递归计算时,如果dp[m][n]计算过,就应该直接取出结果,而不是再次计算。实际中,可以将dp二维数组的初始值设置为-1,如果递归过程中,dp[m][n]!=-1,则表示计算过对应点的路径个数,直接返回结果。
  2. 既然每一行,计算一次就没有用了,那么是否可以将空间复杂度降低?定义dp[m][n]的空间复杂度是m * n,如果只定义一个dp[m],则可以将空间复杂度降低至m

代码

利用递归,空间复杂度m * n

public class Solution {
    
    public int robot(int m, int n, int[][] dp) {
        if(m == 0 || n == 0) {
            return 1;
        }
        
        if(dp[m][n] != -1) {
            return dp[m][n];
        }
        
        dp[m][n] = robot(m - 1, n, dp) + robot(m, n - 1, dp);
        return dp[m][n];
    }
    
    public int uniquePaths(int m, int n) {
        int[][] dp = new int[m][n];
        for(int i = 0; i < m; i++) {
            for(int j = 0; j < n; j++) {
                dp[i][j] = -1;
            }
        }
        return robot(m - 1, n - 1, dp);
    }
}

迭代,空间复杂度m * n

public int uniquePaths(int m, int n) {
    int[][] grid = new int[m][n];
    for(int i = 0; i<m; i++){
        for(int j = 0; j<n; j++){
            if(i==0||j==0)
                grid[i][j] = 1;
            else
                grid[i][j] = grid[i][j-1] + grid[i-1][j];
        }
    }
    return grid[m-1][n-1];
}

进一步优化,空间复杂度m

public class Solution {
    public int uniquePaths(int m, int n) {
        int[] dp = new int[n];
        for(int i = 0; i < m; i++) {
            for(int j = 0; j < n; j++) {
                if(i == 0 || j == 0)
                    dp[j] = 1;
                else if(j > 0)
                    dp[j] += dp[j - 1];
            }
        }
        return dp[n - 1];
    }
}

63. Unique Paths II

Follow up for "Unique Paths":

Now consider if some obstacles are added to the grids. How many unique paths would there be?

An obstacle and empty space is marked as 1 and 0 respectively in the grid.

For example,
There is one obstacle in the middle of a 3x3 grid as illustrated below.

[
  [0,0,0],
  [0,1,0],
  [0,0,0]
]

The total number of unique paths is 2.

Note: m and n will be at most 100.

思路

和上一题很像,只不过增加了一个限制条件:有些点可能不能走。不能走的点,dp变成0就好了。

代码

public class Solution {
    
    public int uniquePathsWithObstacles(int[][] obstacleGrid) {
        int width = obstacleGrid[0].length;
        int[] dp = new int[width];
        dp[0] = 1;
        for(int[] row : obstacleGrid) {
            for(int j = 0; j < width; j++) {
                if(row[j] == 1) 
                    dp[j] = 0;
                else if(j > 0) 
                    dp[j] += dp[j - 1];
            }
        }
        return dp[width - 1];
    }
}

64. Minimum Path Sum

Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which minimizes the sum of all numbers along its path.

Note: You can only move either down or right at any point in time.

思路

定义一个二维数组sum[m][n],表示从(0, 0)到(m - 1, n - 1)的最小的和。所以可以得出公式:

  • sum[0][n] = grid[0][0] + grid[0][4] ... + grid[0][n]
  • sum[m][0] = grid[0][0] + grid[1][0] ... + grid[m][0]
  • sum[m][n] = min(sum[m - 1][n], sum[m][n - 1]) + grid[m][n]

sum[m - 1][n - 1] 即为最终结果。

代码

public class Solution {
    public int minPathSum(int[][] grid) {
        int m = grid.length;
        int n = grid[0].length;
        int[][] sum = new int[m][n];
        sum[0][0] = grid[0][0];
        for(int i = 1; i < m; i++) {
            sum[i][0] += sum[i - 1][0] + grid[i][0];
        }
        for(int j = 1; j < n; j++) {
            sum[0][j] += sum[0][j - 1] + grid[0][j];
        }
        for(int i = 1; i < m; i++) {
            for(int j = 1; j < n; j++) {
                sum[i][j] += Math.min(sum[i - 1][j], sum[i][j - 1]) + grid[i][j];
            }
        }
        return sum[m - 1][n - 1];
    }
}

53. Maximum Subarray

Find the contiguous subarray within an array (containing at least one number) which has the largest sum.

For example, given the array [-2,1,-3,4,-1,2,1,-5,4],
the contiguous subarray [4,-1,2,1] has the largest sum = 6.

思路

设数组sum[i],其中sum[i]表示包括nums[i]的,nums数组从0~i的最大连续和。

  • sum[i] = max(nums[i], sum[i - 1] + nums[i])
  • max = max(sum[i], max)

以题干中的数组[-2,1,-3,4,-1,2,1,-5,4]为例,sum数组为:

[-2, 1, -2, 4, 3, 5, 6, 1, 5]
  • 当i=0时,sum[0] = -2
  • 当i=1时,sum1 = max(nums1, sum[0] + nums1) = max(1, -2 + 1) = 1
  • ……

优化

sum[i]中的每一个数,都只会用到一次。所以可以将sum[i]数组,变成1个变量sum即可,sum的含义与sum[i]相同。

代码

public class Solution {
    public int maxSubArray(int[] nums) {
        if(nums.length == 0) return 0;
        int sum = nums[0], max = nums[0];
        for(int i = 1; i < nums.length; i++) {
            sum = Math.max(nums[i], sum + nums[i]);
            max = Math.max(sum, max);
        }
        return max;
    }
}

总结

对于动态规划的题目,最重要的一步就是写明递推公式初始公式,缓存计算的中间结果,以获取效率。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 157,298评论 4 360
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 66,701评论 1 290
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 107,078评论 0 237
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,687评论 0 202
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,018评论 3 286
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,410评论 1 211
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,729评论 2 310
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,412评论 0 194
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,124评论 1 239
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,379评论 2 242
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 31,903评论 1 257
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,268评论 2 251
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 32,894评论 3 233
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,014评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,770评论 0 192
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,435评论 2 269
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,312评论 2 260

推荐阅读更多精彩内容