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.
机器人走n+m-2步到达终点,其中n-1向右,m-1向下。所以共有Cm-1m+n-2种方法。
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
1 1 1 1 2 1 1 3 3 1 1 4 6 4 1 1 5 10 10 5 1 1 6 15 20 15 6 1 1 7 21 35 35 21 7 1 1 8 28 56 70 56 28 8 1 1 9 36 84 126 126 84 36 9 1 1 10 45 120 210 252 210 120 45 10 1 1 11 55 165 330 462 462 330 165 55 11 1 1 12 66 220 495 792 924 792 495 220 66 12 1...1, C(n-1,1), C(n-1,2), …, C(n-1,n-1) |
int uniquePaths(int m, int n) {
if (m<1||n<1) return 0;
if((m==1)||(n==1)) return 1;
vector<vector<int>> yanghui;
vector<int> temp(1,1);
yanghui.push_back(temp);
for (int i=1;i<=(n+m-2);i++)
{
vector<int> temp1(i+1,0);
temp1[0]=1;
temp1[i]=1;
for (int j=1;j<i;j++)
{
temp1[j]=yanghui[i-1][j-1]+yanghui[i-1][j];
}
yanghui.push_back(temp1);
}
return yanghui[n+m-2][m-1];
}
int uniquePaths(int m, int n) {
int N = n + m - 2;// how much steps we need to do
int k = m - 1; // number of steps that need to go down
double res = 1;
// here we calculate the total possible path number
// Combination(N, k) = n! / (k!(n - k)!)
// reduce the numerator and denominator and get
// C = ( (n - k + 1) * (n - k + 2) * ... * n ) / k!
for (int i = 1; i <= k; i++)
res = res * (N - k + i) / i;
return round(res);//四舍五入,利用math.round()函数。
}
原文:http://blog.csdn.net/sinat_24520925/article/details/45769317