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;
}
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;
}
相关文章推荐
- Leetcode NO.62 Unique Paths
- Leetcode-Unique Paths(dp)
- [leetcode] Unique Paths
- [week 12][Leetcode][Dynamic Programming] Unique Paths
- [LeetCode] Unique Paths
- [leetcode]Unique Paths
- Leetcode 动态规划 Unique Paths
- LeetCode 62 Unique Paths (递推)
- LeetCode 62 Unique Paths
- Unique Paths - LeetCode
- [LeetCode]Unique Paths
- leetcode-62 Unique Paths
- [LeetCode] Unique Paths
- leetcode:Unique Paths
- Leetcode 62 Unique Paths
- LeetCode | Unique Paths
- [LeetCode] Unique Paths
- [LeetCode] Unique Paths、Unique Paths II、Minimum Path Sum
- leetcode - Unique Paths
- leetcode Unique Paths