剑指 Offer 14- II. 剪绳子 II

 

同上一篇剪绳子,题目不同点在于 n 的范围变大,当n过大时,乘积结果过大会导致溢出。

因此不能直接使用动态规划求解。

如果在上题中的动态规划中加入大数运算,虽然能得到结果,但效率过低,如下图所示:

 如果使用上题中的数学方法解题,能正常得出结果,代码如下:

class Solution {
    public int cuttingRope(int n) {
        if (n == 2 || n == 3)
            return n - 1;
        int constant = 1000000007;
        long res = 1;
        while (n > 4) {
            n = n - 3;
            //计算每段的乘积,取模防止溢出
            res = res * 3 % constant;
        }
        return (int) ((res * n) % constant);
    }
}

结果:

 

 参考题解区思路:快速幂

 参考:

https://leetcode-cn.com/problems/jian-sheng-zi-ii-lcof/solution/mian-shi-ti-14-ii-jian-sheng-zi-iitan-xin-er-fen-f/
 
代码如下:时间复杂度:O(logn), 空间复杂度:O(1)
class Solution {
    int mod = 1000000007;
    public int cuttingRope(int n) {
        if(n < 4) return n - 1;
        int a = n / 3;
        int b = n % 3;
        if(b == 0) return (int) (myPow(3, a) % mod);
        else if(b == 1) return (int) (myPow(3, a - 1) * 4 % mod);
        else return (int) (myPow(3, a) * 2 % mod);
    }

    public long myPow(long base, int num){
        long res = 1;
        while(num > 0){
            if((num & 1) == 1){
                res *= base;
                res %= mod;
            }
            base *= base;
            base %= mod;
            num >>= 1;
        }
        return res;
    }
}

作者:ollieq
链接:https://leetcode-cn.com/problems/jian-sheng-zi-ii-lcof/solution/jian-dan-li-jie-dong-tai-gui-hua-xun-hua-4g3o/

结果:

posted @ 2021-02-21 14:24  zjcfrancis  阅读(44)  评论(0编辑  收藏  举报