62.Unique Paths

思路:
  • dfs,超时
class Solution {
public:
    int uniquePaths(int m, int n) {
        return dfs(m,n,0,0);
    }
    int dfs(int m,int n,int curi,int curj){
        if(m-1 == curi && n-1 == curj) {return 1;}
        if(curi > m-1 || curj > n-1) return 0;
        return dfs(m,n,curi,curj+1) + dfs(m,n,curi+1,curj);
    }
};
class Solution {
public:
    int uniquePaths(int m, int n) {
        vector<vector<int>>a(m,vector<int>(n,0));
        return dfs(m-1,n-1,a);
    }
    int dfs(int m,int n,vector<vector<int>>& a){
        if(m < 0 || n < 0) return 0;
        if(m == 0 && n == 0) return 1;
        if(a[m][n] > 0) return a[m][n];
        else return a[m][n] = dfs(m-1,n,a) + dfs(m,n-1,a);
    }
};
  • 组合数学方法。\(m /times n的网格,从\)(0,0)\(走到\)(m-1,n-1)\(共需要\)m+n-2$步,其中 \(m-1\) 步向下,\(n-1\) 步向右。如果把向下走记为 \(0\) ,向右走记为 \(1\) ,相当于\(m-1\)\(0\)\(n-1\)\(1\) 排列组合,共有\(C_{m+n-2}^{m-1}\)
class Solution {
public:
    int uniquePaths(int m, int n) {
        if(m == 1 || n == 1) return 1;
        long long res = 1;
        for(int i = max(m-1,n-1) + 1 ; i <= m+n-2; i++) {   //取,m-1和n-1的最大值,否则可能产生溢出
            res = res*i;
        }
        long long res1 = 1;
        for(int i = 1; i <= min(m-1,n-1); i++){
            res1 = res1*i;
        }
        return (int)(res/res1);
    }
};
  • DP。
class Solution {
public:
    int uniquePaths(int m, int n) {
        vector<int> dp(n);
        dp [0] = 1;
        for(int i = 0; i < m; i++){
            for(int j = 1; j < n; j++){
                dp[j] = dp[j] + dp[j-1];    //等式右边第一个dp相当于dp[i-1][j],第二个dp相当于dp[i][j-1]。
            }
        }
        return dp[n-1];
    }
};
posted @ 2017-06-10 13:33  UniMilky  阅读(121)  评论(0编辑  收藏  举报