面試14題:
題目:剪繩子
題:給你一根長度為n的繩子,請把繩子剪成m段(m,n都是整數,且n>1,m>1),每段繩子的長度記為k[0],k[1],k[2],...,k[m]。請問k[0]*k[1]*...*k[m]可能的最大乘積是多少?例如,當繩子的長度為8時,我們把它剪成長度分別為2,3,3的三段,此時得到的最大乘積為18。
解題思路:基於動態規划和貪婪算法,詳見劍指offer P96
解題代碼:
# -*- coding:utf-8 -*- class Solution: def MaxProductAfterCut(self, n): # 動態規划 if n<2: return 0 if n==2: return 1 if n==3: return 2 products=[0]*(n+1) products[0]=0 products[1]=1 products[2]=2 products[3]=3 for i in range(4,n+1): max=0 for j in range(1,i//2+1): product=products[j]*products[i-j] if product>max: max=product products[i]=max #print(products) return products[n] def MaxProductAfterCut2(self, n): # 貪婪算法 if n < 2: return 0 if n==2: return 1 if n==3: return 2 timesOf3 = n//3 if n - timesOf3*3 == 1: timesOf3 -= 1 timesOf2 = (n - timesOf3 * 3)//2 return (3**timesOf3) * (2**timesOf2) if __name__=="__main__": print(Solution().MaxProductAfterCut(8)) print(Solution().MaxProductAfterCut(10)) #print(Solution().NumberOf1(0)) print(Solution().MaxProductAfterCut2(8)) print(Solution().MaxProductAfterCut2(10))