剪绳子I
贪心:时间O(1),空间O(1)
题解:
- 一般情况下绳子分的段数越多,乘积也就越大
- 为了使乘积更大,分得段数 3 越多,结果也就越大
- 若以每段长 3 分得剩下长度为1,则把最后一节分成 2 * 2 > 1 * 3
class Solution {
public:
int cuttingRope(int n)
{
// 1.数学,贪心
if (n < 4)
return n - 1;
int count = n / 3;
int mod = n % 3; // mod只能是0,1,2
if (mod == 1)
{
mod = 4;
count--;
}
else if (mod == 0)
mod = 1;
return pow(3, count) * mod;
}
};
剪绳子II:
贪心 + 快速幂:时间O(logn),空间O(1)
题解:
- 这里在上个题的基础上增加了取模的条件,也就是结果很大,可能使整数溢出
- 常规求幂的时间复杂度为O(n),二分法求幂可以把时间复杂度降至O(logn)
class Solution {
public:
int mod = 1000000007;
long long MY_POW(long long x, int n)
{
long long res = 1;
while (n)
{
if (n & 1) // 若n为奇数,则需要乘单独的x
{
res = res * x % mod;
}
// x^n = (x^2)^(n/2)
x = x * x % mod;
n /= 2;
}
return res;
}
int cuttingRope(int n)
{
if (n < 4)
return n - 1;
int x = n / 3;
int y = n % 3; // y只有0,1,2三种取值
if (y == 1)
return MY_POW(3, x - 1) * 4 % mod;
else if (y == 2)
return MY_POW(3, x) * 2 % mod;
else
return MY_POW(3, x);
}
};