代码随想录算法训练营第三十九天 | 62. 不同路径 | 63. 不同路径 II

62. 不同路径     

1. 确定dp数组下标含义 dp[i][j] 到每一个坐标可能的路径种类
2. 递推公式 dp[i][j] = dp[i-1][j] dp[i][j-1]
3. 初始化 dp[i][0]=1 dp[0][i]=1 初始化横竖就可
4. 遍历顺序 一行一行遍历
5. 推导结果 

class Solution {
    public int uniquePaths(int m, int n) {
        int[][] dp = new int[m][n]; 
        //初始化
        for (int i = 0; i < m; i++) {
            dp[i][0] = 1;
        }
        for (int i = 0; i < n; i++) {
            dp[0][i] = 1;
        }

        for (int i = 1; i < m; i++) {
            for (int j = 1; j < n; j++) {
                dp[i][j] = dp[i-1][j]+dp[i][j-1];
            }
        }
        return dp[m-1][n-1];
    }
}

63. 不同路径 II

与上一题类似,多了个障碍物条件判断

class Solution {
    public int uniquePathsWithObstacles(int[][] obstacleGrid) {
        int m = obstacleGrid.length;
        int n = obstacleGrid[0].length;
        int[][] dp = new int[m][n];

        //如果在起点或终点出现了障碍,直接返回0
        if (obstacleGrid[m - 1][n - 1] == 1 || obstacleGrid[0][0] == 1) {
            return 0;
        }

        for (int i = 0; i < m && obstacleGrid[i][0] == 0; i++) {
            dp[i][0] = 1;
        }
        for (int j = 0; j < n && obstacleGrid[0][j] == 0; j++) {
            dp[0][j] = 1;
        }

        for (int i = 1; i < m; i++) {
            for (int j = 1; j < n; j++) {
                dp[i][j] = (obstacleGrid[i][j] == 0) ? dp[i - 1][j] + dp[i][j - 1] : 0;
            }
        }
        return dp[m - 1][n - 1];
    }
}

你可能感兴趣的:(算法,动态规划,数据结构)