栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

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

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

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

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

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/21137.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号