您的位置:首页 > 编程语言 > Python开发

Python 剪绳子的多种思路实现(动态规划和贪心)

2020-04-21 07:24 1141 查看

剑指Offer(Python多种思路实现):剪绳子

面试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。

解题思路一:基于动态规划和贪婪算法。

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


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))

解题思路二:基于动态规划和贪婪算法。

class Solution:
# 动态规划
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

# 贪婪算法
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)

到此这篇关于Python 剪绳子的多种思路实现(动态规划和贪心)的文章就介绍到这了,更多相关Python 剪绳子内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Python 剪绳子