日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

剪绳子python_Python剪绳子如何实现 Python剪绳子实现代码

發(fā)布時間:2025/4/5 python 23 豆豆
生活随笔 收集整理的這篇文章主要介紹了 剪绳子python_Python剪绳子如何实现 Python剪绳子实现代码 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

本篇文章小編給大家分享一下Python剪繩子實現(xiàn)代碼,小編覺得挺不錯的,現(xiàn)在分享給大家供大家參考,有需要的小伙伴們可以來看看。

題目:剪繩子

給你一根長度為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)

《新程序員》:云原生和全面數(shù)字化實踐50位技術(shù)專家共同創(chuàng)作,文字、視頻、音頻交互閱讀

總結(jié)

以上是生活随笔為你收集整理的剪绳子python_Python剪绳子如何实现 Python剪绳子实现代码的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。