美文网首页
LeetCode-Uniqpaths II

LeetCode-Uniqpaths II

作者: 圣地亚哥_SVIP | 来源:发表于2018-10-12 16:32 被阅读0次

    题目要求:
    相比较于Unique Paths,多了一些限制,某些obstaclegrid=1的位置不能作为路径。
    方法一样,采用动态规划,添加一些限制:
    Method: flag[i][j] = obstacleGrid[i][j]==1? 0:flag[i-1][j]+flag[i][j-1];

    class Solution {
    public:
        void non_uniqpath(vector<vector<int>>& obstacleGrid,int& num){
            int m = obstacleGrid.size();
            int n = obstacleGrid[0].size();
            vector<vector<int>> flag;
            flag.resize(m);
            for_each(flag.begin(),flag.end(),[n](vector<int>& pa){pa.resize(n,0);});
            flag[0][0] = obstacleGrid[0][0]==1? 0:1;
            for (int i=1;i<n;i++){
                flag[0][i] = obstacleGrid[0][i]==1? 0:flag[0][i-1];
            }
            for (int i=1;i<m;i++){
                flag[i][0] = obstacleGrid[i][0]==1? 0:flag[i-1][0];
            }
            for (int i=1;i<m;i++){
                for (int j=1;j<n;++j){
                    flag[i][j] = obstacleGrid[i][j]==1? 0:flag[i-1][j]+flag[i][j-1];
                }
            }
            num = flag[m-1][n-1];
        }
        int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) {
            int num=0;
            non_uniqpath(obstacleGrid,num);
            return num;
        }
    };
    

    相关文章

      网友评论

          本文标题:LeetCode-Uniqpaths II

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