// 暴力解法+备忘录减少运算量 classSolution{ publicintcuttingRope(int n){ int[] f=newint[n+1]; return mem(f,n); } publicintmem(int[] f,int n){ if(f[n]!=0){ return f[n]; } if (n == 2) return1; int res = -1; for (int i = 1; i <= n - 1; i++) { res = Math.max(res, Math.max(i * (n - i), i * mem(f,n - i))); } f[n]=res; return res; } }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
# 使用辅助函数 classSolution: defcuttingRope(self, n: int) -> int: defmemoize(n): if n == 2: return1 if f[n] != 0: # 如果f[n]已经计算过,直接返回避免重复计算 return f[n] res = -1 for i in range(1, n): res = max(res, max(i * (n - i),i * memoize(n - i))) f[n] = res return res
classSolution: defcuttingRope(self, n: int) -> int: if n <= 3: return n - 1 a, b, p, x, rem = n // 3 - 1, n % 3, 1000000007, 3 , 1 while a > 0: if a % 2: rem = (rem * x) % p x = x ** 2 % p a //= 2 if b == 0: return (rem * 3) % p # = 3^(a+1) % p if b == 1: return (rem * 4) % p # = 3^a * 4 % p return (rem * 6) % p # = 3^(a+1) * 2 % p # 由于语言特性,Python 可以不考虑大数越界问题 classSolution: defcuttingRope(self, n: int) -> int: if n <= 3: return n - 1 a, b, p = n // 3, n % 3, 1000000007 if b == 0: return3 ** a % p if b == 1: return3 ** (a - 1) * 4 % p return3 ** a * 2 % p
publicclassSolution{ // you need to treat n as an unsigned value publicinthammingWeight(int n){ // 普通遍历法 int res=0; while(n!=0){ res+=n&1; n>>>=1; } return res; } }
1 2 3 4 5 6 7 8
classSolution: defhammingWeight(self, n: int) -> int: #普通遍历法 res=0 while n: res+=n&1 n>>=1 return res
publicclassSolution{ // you need to treat n as an unsigned value publicinthammingWeight(int n){ int res=0; while(n!=0){ res++; n=n&(n-1); } return res; } }
1 2 3 4 5 6 7 8
classSolution: defhammingWeight(self, n: int) -> int: # 借助n-1 res=0 while n: res+=1 n=n&(n-1) return res