算法训练营Day39(动态规划)

62.不同路径

62. 不同路径 - 力扣(LeetCode)

java 复制代码
class Solution {
    public int uniquePaths(int m, int n) {
        //1dp数组  m n代表位置,dp[m][n]代表到达这里的途径个数
        int [][] dp = new int[m][n];
        //3初始化
        for(int i = 0;i<n;i++){
            dp[0][i] = 1;
        }
        for(int j = 0;j<m;j++){
            dp[j][0] = 1;
        }
        //4遍历顺序
        for(int i = 1;i<m;i++){
            for(int j = 1;j<n;j++){
                //2递推公式
                dp[i][j] = dp[i-1][j]+dp[i][j-1]; 
            }
        }
        return dp[m-1][n-1];
    }
}

63. 不同路径 II

63. 不同路径 II - 力扣(LeetCode)

java 复制代码
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<n;i++){
            if(obstacleGrid[0][i]==1){
                break;
            }
            dp[0][i]=1;
        }
        for(int j=0;j<m;j++){
            if(obstacleGrid[j][0]==1) break;
            dp[j][0] = 1;
        }

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

    }
}
相关推荐
呆呆的小鳄鱼14 分钟前
leetcode:冗余连接 II[并查集检查环][节点入度]
算法·leetcode·职场和发展
墨染点香15 分钟前
LeetCode Hot100【6. Z 字形变换】
java·算法·leetcode
沧澜sincerely15 分钟前
排序【各种题型+对应LeetCode习题练习】
算法·leetcode·排序算法
CQ_071216 分钟前
自学力扣:最长连续序列
数据结构·算法·leetcode
弥彦_31 分钟前
cf1925B&C
数据结构·算法
YuTaoShao1 小时前
【LeetCode 热题 100】994. 腐烂的橘子——BFS
java·linux·算法·leetcode·宽度优先
Wendy14418 小时前
【线性回归(最小二乘法MSE)】——机器学习
算法·机器学习·线性回归
拾光拾趣录9 小时前
括号生成算法
前端·算法
渣呵9 小时前
求不重叠区间总和最大值
算法
拾光拾趣录10 小时前
链表合并:双指针与递归
前端·javascript·算法