Python 剪繩子的多種思路實現(xiàn)(動態(tài)規(guī)劃和貪心)
劍指Offer(Python多種思路實現(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]可能的最大乘積是多少?例如,當繩子的長度為8時,我們把它剪成長度分別為2,3,3的三段,此時得到的最大乘積為18。
解題思路一:基于動態(tài)規(guī)劃和貪婪算法。
class Solution:
def MaxProductAfterCut(self, n):
# 動態(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))
解題思路二:基于動態(tài)規(guī)劃和貪婪算法。
class Solution:
# 動態(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 剪繩子的多種思路實現(xiàn)(動態(tài)規(guī)劃和貪心)的文章就介紹到這了,更多相關(guān)Python 剪繩子內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
PyTorch中關(guān)于tensor.repeat()的使用
這篇文章主要介紹了PyTorch中關(guān)于tensor.repeat()的使用,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-11-11

