剑指 Offer 14- II. 剪绳子 II
链接:https://leetcode-cn.com/problems/jian-sheng-zi-ii-lcof/
剪绳子的思想跟https://blog.youkuaiyun.com/breeze_blows/article/details/107869399是一致的,只是这里涉及到大数,所以用到快速幂:https://zhuanlan.zhihu.com/p/95902286
时间复杂度:O(log2n),快速幂的时间复杂度,其实就是移位或者说除以2的时间复杂度
空间复杂度:O(1)
class Solution:
def cuttingRope(self, n: int) -> int:
if n <= 3:
return n-1
#n = 3*(a-1)*3 + b
"""
n%3 == 0: 3**(n//3)
n%3 == 1: 3**(n//3-1)*4
n%3 == 2: 3**(n//3)*2
所以下面计算3**(n//3-1)
"""
x, a, b, rem = 3, n//3-1, n%3, 1
p = 1000000007
while a:
if a%2:
rem = rem*x % p
x = x**2 % p
a = a//2
if b == 0:
return rem*3 % p
elif b == 1:
return rem*4 % p
else:
return rem*6 % p