Unique Paths - Dynamic Programming (Basic)

C++ solution - 0ms

class Solution {
public:
    int uniquePaths(int m, int n) {

        ios::sync_with_stdio(false);
        cin.tie(NULL);
        cout.tie(NULL);

        vector<vector<int>> dp(m, vector<int>(n));
        for(int i=0; i<m; i++) {
            for(int j=0; j<n; j++) {
                if(i==0 || j==0) {
                    dp[i][j] = 1;    // to go at location i=0 or j=0, you will have only one path
                }
                else dp[i][j] = dp[i-1][j] + dp[i][j-1];  // no of paths at i, j will be sum of no of paths of above cell and left cell 
            }
        }
        return dp[m-1][n-1];
    }
};
Comments (0)