这样一道题目:
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?
这道题目看起来不难,但是需要一些的排列组合的数学功底。
第一次的思路是错的:以为是将向从向下走的步子为基本点,然后向里面穿插想右走的步数。实际上并非如此。以为如果第一步向下之后则回到了这一种情况。
重新思考了一下应该是这个样子。从两个方向的步数之和里面组挑出向右或者向下的步数。
思路已经确定,通过了几个用例,但是其实这里面的考点是越界的问题。
直接写出阶乘公式再进行相处更是会得到更大的中间数据(尽管数学表达式可以这样表示,但是工程中不能直接拿过来运算)。发现相除以后可以约去一些,就写了一个可以从a+1累乘到b的函数(可以完成排列)。但是还是需要一个阶乘函数来完成组合,不过这样的中间数据至于过大。
但是当 10! 运算的时候其范围就会超过int(32位)的范围。而导致越界。
于是考虑使用long作为中间数据类型。
结尾需要转化回int。
发现平台不支持强制转化,于是有了
Long(longNum).intValue();
的想法。成功了。
总结
1. 逻辑上一定要先准确,再开始编码。多多利用公式推导出清晰的结果在进行编码。不要急于计算。
2. 对于大数计算的处理应该还会有一些题目。要多多了解方法。
附上带有accpted的代码:
public class Solution {
int node;
int line;
//we need a function to realize factorial calculation
private long likeFactorial(int low,int hight){//calc factorial from low number to hight number
long result=1;
for(int i=low+1;i<=hight;i++){
result*=i;
}
return result;
}
private long factorial(int num){
long result=1;
for(int i=1;i<=num;i++){
result*=i;
}
return result;
}
public int uniquePaths(int m, int n) {
if(m>=n){
node=n-1;//for the step is less one than the grid number
line=m-1;
}else{
node=m-1;
line=n-1;
}
if(node==0||line==0){//if only one grid,prevant situations devided by zero.
return 1;
}
int result=new Long(likeFactorial(line,line+node)/factorial(node)).intValue();
return result;
}
}