LeetCode百钱买百鸡python递归解法示例
作者:voyage200
这篇文章主要为大家介绍了LeetCode百钱买百鸡题目python递归解法示例,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
plan A
#公鸡5文钱一只 母鸡3文钱一只 小鸡1文钱 三只 money = 100 def buy_kun(gong:int,mu:int,xiao:int,c:int) -> None: if gong*5+mu*3+xiao > money or gong+mu+xiao*3>100: return if gong*5+mu*3+xiao == money and gong+mu+xiao*3==100: print(f'买{gong}只公鸡,{mu}只母鸡,{xiao*3}只小鸡,刚好凑够{money}文钱。') return if c<1 : buy_kun(gong+1,mu,xiao,0) if c<2: buy_kun(gong,mu+1,xiao,1) if c<3: buy_kun(gong,mu,xiao+1,2) buy_kun(0,0,0,0)
plan B
参考:## 状态转移解法(递归)
# (公鸡数,母鸡数,小鸡数,总钱数,总鸡数),状态转移 import numpy as np # 导入numpy库 st = np.zeros((100, 100, 100)) # 新建三维数组,且初始值为0,记录状态是否被遍历过,进行剪枝操作 def resolve(a, b, c, d, e): if d == 100 and e == 100: print("%s只公鸡,%s只母鸡,%s只小鸡" % (a, b, c)) else: a1 = a + 1 b1 = b + 1 c1 = c + 3 if d + 5 <= 100 and e + 1 <= 100 and st[a1][b][c] == 0: st[a1][b][c] = 1 resolve(a1, b, c, d + 5, e + 1) if d + 3 <= 100 and e + 1 <= 100 and st[a][b1][c] == 0: st[a][b1][c] = 1 resolve(a, b1, c, d + 3, e + 1) if d + 1 <= 100 and e + 3 <= 100 and st[a][b][c1] == 0: st[a][b][c1] = 1 resolve(a, b, c1, d + 1, e + 3) # (公鸡数,母鸡数,小鸡数,总钱数,总鸡数) resolve(0, 0, 0, 0, 0)
## 运行结果
小结
#公鸡5文钱一只 母鸡3文钱一只 小鸡1文钱 三只 import numpy as np st = np.zeros((100, 100, 100)) money = 100 def buy_kun(gong:int,mu:int,xiao:int) -> None: if st[gong][mu][xiao] == 1: return else: st[gong][mu][xiao] = 1 if gong*5+mu*3+xiao > money or gong+mu+xiao*3>100: return if gong*5+mu*3+xiao == money and gong+mu+xiao*3==100: print(f'买{gong}只公鸡,{mu}只母鸡,{xiao*3}只小鸡,刚好凑够{money}文钱。') return buy_kun(gong+1,mu,xiao) buy_kun(gong,mu+1,xiao) buy_kun(gong,mu,xiao+1) buy_kun(0,0,0)
以上就是LeetCode百钱买百鸡python递归解法示例的详细内容,更多关于百钱买百鸡python递归解法的资料请关注脚本之家其它相关文章!