62. Unique Paths

A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below).

The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below).

How many possible unique paths are there?
62. Unique Paths_第1张图片

动态规划

很明显可以看出dp[m][n] = dp[m-1][n] + dp[m][n-1]
初始化 dp[1][j]、dp[j][1] 然后递推即可

class Solution {
public:
    //dp[m][n] = dp[m-1][n] + dp[m][n-1]
    int uniquePaths(int m, int n) {
        int dp[m + 1][n + 1];
        for(int j = 1; j <= n; j++ ) dp[1][j] = 1;
        for(int j = 1; j <= m; j++ ) dp[j][1] = 1;
            
        for(int i = 2; i <= m; i++ ){
            for(int j = 2; j <=n; j++){
                dp[i][j] = dp[i-1][j] + dp[i][j-1]; 
            }
        }
        return dp[m][n];
    }
};

数学方法

排列组合:C(m + n - 2, n - 1)
从 m + n - 2 选出 n - 1 步向右走

class Solution {
public:
    //C(n, m)
    int Combination(int n, int m) 
    { 
        long long result = 1;
        for(int i = 1; i <= m; i++){
            result = result * (n - i + 1) / i;
        }
        return result;
    }   
    
    int uniquePaths(int m, int n) {
       return Combination(m + n - 2, min(m - 1, n - 1));
    }
};

注意必须 min(m - 1, n - 1) 不然 long long 会溢出

你可能感兴趣的:(62. Unique Paths)