[LeetCode] Unique Paths

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?


Above is a 3 x 7 grid. How many possible unique paths are there?

Note: m and n will be at most 100.

解题思路:

数学题。共有路径数C(m-1 + n - 1, n-1)。计算的时候会用到阶层运算,因此要用longlong类型防止溢出,而且需要尽量先做除法运算。

class Solution {
public:
    int uniquePaths(int m, int n) {
        long long result = 1;
        if(m<=1 || n<=1){
            return result;
        }
        int j=n-1;
        for(int i=m+n-2; i>=m; i--){
            while(j>1 && result%j==0){
                result = result/j;
                j--;
            }
            result = result * i;
        }
        while(j>1 && result%j==0){
            result = result/j;
            j--;
        }
        return (int)result;
    }
};

update in 2015-07-28

方法2:回溯法。

d[i][j]表示从0,0到i,j的走法数,则有

d[i][j]=d[i-1][j]+d[i][j-1]

代码如下:

class Solution {
public:
    int uniquePaths(int m, int n) {
        if(m<=0||n<=0){
            return 0;
        }
        vector<vector<int>> d(m, vector<int>(n, 0));
        d[0][0] = 1;
        for(int i=0; i<m; i++){
            for(int j=0; j<n; j++){
                if(i>0){
                    d[i][j] += d[i-1][j];
                }
                if(j>0){
                    d[i][j] += d[i][j-1];
                }
            }
        }
        return d[m-1][n-1];
    }
};

你可能感兴趣的:(LeetCode,C++)