【LeetCode】爬楼梯,遇到的问题

论坛 期权论坛 脚本     
匿名技术用户   2020-12-27 02:44   274   0

发现 阶乘太厉害了 ,这样搞很容易溢出,导致计算出错。


class Solution {
public:
    int climbStairs(int n) {
        int ret=0;
        for(int i=0;i<=n/2;i++)
        {
            int nSteps=n;
            nSteps=nSteps-i*2;
            
            ret+=calculate(i,nSteps);
            printf("the i=%d,the nStep=%d,the ret=%d\n",i,nSteps,ret);
        }
        return ret;
    }
    //permutation 排列     //combination 组合
    int calculate(int a,int b)
    {
        
        return (int)(factorial(a+b)/(factorial(a)*factorial(b)));
    }
    
    //factorial 阶乘
    unsigned long long factorial(unsigned long long n)
    {
        unsigned long long ret=1;
        for(int i=1;i<=n;i++)
        {
            ret*=i;
        }
        return ret;
    }
    
};


分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:7942463
帖子:1588486
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP