Unique Paths -leetcode

这样一道题目:

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;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小马工匠坊

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值