美文网首页
leetcode_63不同路径2

leetcode_63不同路径2

作者: 看到这朵小fa了么 | 来源:发表于2020-07-06 11:27 被阅读0次

    动态规划,目标值所有路径为其上或者其左的路径之和,转移方程:f[m,n]=f[m-1][n]+f[m][n-1]
    初始化f为0,第一个值为0则置为f[0][0]1,遇到障碍物1置为0

    var uniquePathsWithObstacles = function(obstacleGrid) {
        let rows = obstacleGrid.length
        let colums = obstacleGrid[0].length
        let result = []
       for(let i=0; i<rows; i++){
           result[i] = Array(colums).fill(0)
           for(let j=0; j<colums; j++) {
             if(obstacleGrid[i][j]===0) {
                 if(i===0 && j===0) {
                     result[0][0] = 1
                 }
                 if(i-1>=0 && j-1>=0) {
                  result[i][j] = result[i-1][j] + result[i][j-1]
                 } else if(i-1>=0) {
                     result[i][j] = result[i-1][j]
                 } else if(j-1>=0) {
                    result[i][j] = result[i][j-1]
                 }
                
             }
           }
       }
       return result[rows-1][colums-1]
    };
    

    相关文章

      网友评论

          本文标题:leetcode_63不同路径2

          本文链接:https://www.haomeiwen.com/subject/gtdwqktx.html