func cuttingRope(_ n: Int) -> Int {
if n < 4 {
return n - 1
}
var dp = [Int](repeating: 1, count: n + 1)
for i in 3...n {
for j in 2..<i {
dp[i] = max(dp[i], max(j * (i - j), j * dp[i - j]))
}
}
return dp[n] % 1_000_000_007
}
试试两个测试用例:
10 - 36
2 - 1
很正常没问题嘛~🤷♂️
2.2 试试120
居然出错了?
2.3 数据长度问题
请注意本题的数据范围 2 <= n <= 1000 和第一题的 2 <= n <= 58,差别很大。
上面报错就是因为数据超出了范围了。
那你可能会想到,那我换 Int64 ?我换 long ?
然鹅并不行
那我每次纯数据都取一下模?
更不行,中间数据都变了,结果当然更错
我们用 Decimal 来接收看看120时到底是多大:
120 时就已经 20位 了,更何况本题的范围最大1000。
我们就不要再数据类型的选择上进行纠结了
2.4 Decimal 解法
这里将元素使用 Decimal 进行承载
let base = NSDecimalNumber(decimal: Decimal(1_000_000_007))
func cuttingRope(_ n: Int) -> Int {
if n < 4 {
return n - 1
}
var dp = [Decimal](repeating: 1, count: n + 1)
for i in 3...n {
for j in 2..<i {
dp[i] = max(dp[i], max(Decimal(j) * Decimal(i - j), Decimal(j) * dp[i - j]))
}
}
let handler = NSDecimalNumberHandler(roundingMode: .down, scale: 0, raiseOnExactness: false, raiseOnOverflow: false, raiseOnUnderflow: false, raiseOnDivideByZero: false)
let result = NSDecimalNumber(decimal: dp[n])
let baseCount = result.dividing(by: base).rounding(accordingToBehavior: handler)
let tp = result.subtracting(base.multiplying(by: baseCount))
return Int(truncating: tp)
}
结果到 255 的时候还是错了,还是丢失了精度。毕竟 NSDecimalNumber 也是有范围的
感觉想继续用动态规划不太现实了
2.5 补充 Java 的 BigInteger 可以动态规划
import java.math.BigInteger;
class Solution {
public int cuttingRope(int n) {
BigInteger[] dp = new BigInteger[n + 1];
Arrays.fill(dp, BigInteger.valueOf(1));
// dp[1] = BigInteger.valueOf(1);
for(int i = 3; i < n + 1; i++){
for(int j = 1; j < i; j++){
dp[i] = dp[i].max(BigInteger.valueOf(j * (i - j))).max(dp[i - j].multiply(BigInteger.valueOf(j)));
}
}
return dp[n].mod(BigInteger.valueOf(1000000007)).intValue();
}
}
func cuttingRope(_ n: Int) -> Int {
if n < 4 {
return n - 1
}
var res = 1
var n = n
while n > 4 {
res = res * 3 % 1_000_000_007
n -= 3
}
return res * n % 1_000_000_007
}
func cuttingRope(_ n: Int) -> Int {
if n < 4 {
return n - 1
}
let a = n / 3, b = n % 3
if b == 0 {
return modPow(3, a) % 1_000_000_007
}
else if b == 1 {
return modPow(3, a - 1) * 4 % 1_000_000_007
}
else {
return modPow(3, a) * 2 % 1_000_000_007
}
}
func modPow(_ x: Int, _ n: Int) -> Int {
var res = 1
var x = x
var n = n
while n > 0 {
if n & 1 == 1 {
res *= x
res %= 1_000_000_007 // 限制了数据范围
}
x *= x
x %= 1_000_000_007 // 限制了数据范围
n >>= 1
}
return res
}