Python 剪繩子的多種思路實(shí)現(xiàn)(動(dòng)態(tài)規(guī)劃和貪心)
劍指Offer(Python多種思路實(shí)現(xiàn)):剪繩子
面試14題:
題目:剪繩子
題:給你一根長度為n的繩子,請把繩子剪成m段(m,n都是整數(shù),且n>1,m>1),每段繩子的長度記為k[0],k[1],k[2],...,k[m]。請問k[0]*k[1]*...*k[m]可能的最大乘積是多少?例如,當(dāng)繩子的長度為8時(shí),我們把它剪成長度分別為2,3,3的三段,此時(shí)得到的最大乘積為18。
解題思路一:基于動(dòng)態(tài)規(guī)劃和貪婪算法。
class Solution: def MaxProductAfterCut(self, n): # 動(dòng)態(tài)規(guī)劃 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))
解題思路二:基于動(dòng)態(tài)規(guī)劃和貪婪算法。
class Solution: # 動(dòng)態(tài)規(guī)劃 def maxCut(self, n): if n<2: return 0 if n==2: return 1 if n==3: return 2 res=[0]*(n+1) res[0], res[1], res[2], res[3]=0, 1, 2, 3 for i in range(4, n+1): max = 0 for j in range(1, i//2+1): temp = res[j]*res[i-j] if temp>max: max = temp res[i]=max # 由下而上 return res[n] # 貪婪算法 def cutRope(length): if length<2: return 0 if length==2: return 1 if length==3: return 2 timesOf3 = length // 3 # 盡可能剪出3 if length-timesOf3*3 == 1: # 如果最后余1,則留一段4分成兩半 timesOf3 -= 1 timesOf2 = (length-timesOf3*3) // 2 return (3**timesOf3) * (2**timesOf2)
到此這篇關(guān)于Python 剪繩子的多種思路實(shí)現(xiàn)(動(dòng)態(tài)規(guī)劃和貪心)的文章就介紹到這了,更多相關(guān)Python 剪繩子內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- C語言動(dòng)態(tài)規(guī)劃之背包問題詳解
- java背包問題動(dòng)態(tài)規(guī)劃算法分析
- 淺析python實(shí)現(xiàn)動(dòng)態(tài)規(guī)劃背包問題
- 背包問題-動(dòng)態(tài)規(guī)劃java實(shí)現(xiàn)的分析與代碼
- python動(dòng)態(tài)規(guī)劃算法實(shí)例詳解
- java動(dòng)態(tài)規(guī)劃算法——硬幣找零問題實(shí)例分析
- Java面試之動(dòng)態(tài)規(guī)劃與組合數(shù)
- python實(shí)現(xiàn)最大子序和(分治+動(dòng)態(tài)規(guī)劃)
- 詳解DAG上的DP
相關(guān)文章
Python+OpenCV實(shí)現(xiàn)六種常用圖像特效
這篇文章主要為大家介紹了用Python和OpenCV實(shí)現(xiàn)的六種常見圖像特效:圖像融合、灰度處理、馬賽克效果、浮雕效果、毛玻璃效果和顏色反轉(zhuǎn),需要的可以參考一下2022-05-05PyTorch中關(guān)于tensor.repeat()的使用
這篇文章主要介紹了PyTorch中關(guān)于tensor.repeat()的使用,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-11-11使用python繪制cdf的多種實(shí)現(xiàn)方法
今天小編就為大家分享一篇使用python繪制cdf的多種實(shí)現(xiàn)方法,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-02-02Python實(shí)現(xiàn)自動(dòng)簽到腳本功能
這篇文章主要介紹了Python實(shí)現(xiàn)自動(dòng)簽到腳本,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-08-08