Unique Paths
来源:互联网 发布:淘宝怎么提高店铺权重 编辑:程序博客网 时间:2024/06/09 13:41
Problem:
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+n-2,m-1)。
用组合数公式C(n,k)=C(n,k-1)*(n-k+1)/k。
因为C(n,k)=C(n,n-k),所以选择min(m-1,n-1)做为公式中的k能够减少迭代计算次数。注意把乘法运算转换为long防止中间结果溢出。
Solution:
public class Solution {
public int uniquePaths(int m, int n) {
if(m<=0||n<=0)
return 0;
int p = Math.min(m-1, n-1),q = m+n-2;
int tmp = 1;
for(int k=1;k<=p;k++)
{
tmp = (int)((long)(q-k+1)*tmp/k);
}
return tmp;
}
}
public int uniquePaths(int m, int n) {
if(m<=0||n<=0)
return 0;
int p = Math.min(m-1, n-1),q = m+n-2;
int tmp = 1;
for(int k=1;k<=p;k++)
{
tmp = (int)((long)(q-k+1)*tmp/k);
}
return tmp;
}
}
0 0
- Unique Paths
- Unique Paths
- Unique Paths
- Unique Paths
- Unique Paths
- Unique Paths
- Unique Paths
- Unique Paths
- Unique Paths
- Unique Paths
- Unique Paths
- Unique Paths
- Unique Paths
- Unique Paths
- Unique Paths
- Unique Paths
- Unique Paths
- Unique Paths
- 【bellman_ford】poj2240
- 零点常数
- 使用python批量修改文件的后缀
- 理解文件的属性
- Palindromic Subsequence(最长回文字符串 输出路径)
- Unique Paths
- 强烈的范围
- union
- 【spfa(栈)或者 堆优dijkstra】poj3159
- 海量数据框架变迁——阿里巴巴上市背后的技术力量
- 变量被删除
- 再谈hashCode和equals
- 状态机的实现
- 内存位置不在堆叠