思路
思路參考自面試題14- II. 剪繩子 II(貪心 + 快速冪求餘,清晰圖解)
代碼
class Solution {
public:
const int m = 1e9 + 7;
int cuttingRope(int n)
{
//特判
if (n == 2) return 1;
if (n == 3) return 2;
//貪心
//當n>3時,求n除以3的整數部分a和餘數部分b(即n=3a+b),並分爲以下三種情況
if (n % 3 == 1) return (CalculateProduce(3, n / 3 - 1) * 4) % m; //b==1
else if (n % 3 == 2) return (CalculateProduce(3, n / 3) * 2) % m; //b==2
else return (CalculateProduce(3, n / 3)) % m; //b==0
}
//循環求餘法
long long int CalculateProduce(int n, int k)
{
long long int res = 1;//由於res*n可能超過int,因此要先使用longlong進行存儲
for (int i=0;i<k;i++)
{
res = (res * n % m);
}
return res;
}
};