剑指 Offer 14- II. 剪绳子 II(中等)

发布时间 2023-09-01 20:35:33作者: 孜孜不倦fly

题目:

class Solution {      //本题用贪心算法,拆成尽可能多的3且不可以出现长度为1的小段。用dp会溢出,放弃吧
public:
    int cuttingRope(int n) {
        if(n==2) return 1;
        if(n==3) return 2;
        if(n==4) return 4;        
        long long res = 1;
        while(n>4){      //当n<=4的时候不再分割
            n-=3;
            res = 3*res%1000000007;
        }
        res = n*res%1000000007;
        return (int)res;      //强制转换成int
    }
};