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

作者:袖梨 2020-02-24

本篇文章小编给大家分享一下Python剪绳子实现代码,小编觉得挺不错的,现在分享给大家供大家参考,有需要的小伙伴们可以来看看。

题目:剪绳子

给你一根长度为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[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))

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

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

相关文章

精彩推荐