您的位置:首页 > 产品设计 > UI/UE

LeetCode: Unique Paths

2016-09-19 12:02 441 查看
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.

题目解析:可以看作是组合问题。一共(m+n)步,需要n步向右,既C(n, m+n)

int uniquePaths(int m, int n) {
if (m <= 0 || n <= 0) return 0;
if (m == 1 || n == 1) return 1;

n -= 1;
m -= 1;

if (n > m) {
int t = n;
n = m;
m = t;
}

long top = 1;
long bottom = 1;
for(int i = m + 1; i <= m + n; ++i) {
top *= i;
}

for (int i = 2; i <= n; ++i) {
bottom *= i;
}

return top / bottom;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息