Dynamic Programming - 63. Different Paths II

### Problem-solving ideas

Dynamic Programming with Rolling Array Optimization

How to judge it is dynamic programming?

Analyze the topic and discover the no aftereffects and optimal sub-problems (optimal sub-structures)

No aftereffect: The solution of the current problem is only related to the solution of the previous problem and has nothing to do with the solution of the subsequent problem.

Optimal subproblem: The optimal solution of the current problem depends on the optimal solution of the subproblem, and there is a recursive relationship between the two.

 

class Solution {
public:
    int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) {
        if(obstacleGrid.size() == 0 || obstacleGrid[0].size()==0) return 0;
        int m = obstacleGrid.size();
        int n= obstacleGrid[0].size();
        vector<int> dp(n, 0);

        if(obstacleGrid[0][0] == 0) dp[0] = 1;

        for(int i=0;i<m;i++){
            for(int j=0;j<n;j++){
                if(obstacleGrid[i][j]==1){
                    dp[j]=0;
                    continue;
                }
                if(j>=1) dp[j] = dp[j] + dp[j-1];//cur = up +  left

            }
        }
        return dp[n-1];

    }
};

Guess you like

Origin blog.csdn.net/xihuanniNI/article/details/125556988