开发者

LeetCode百钱买百鸡python递归解法示例

目录
  • plan A
  • plan B
  • 小结

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 == 1编程00 and e == 100:
        pphprint("%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)

## 运行结果

LeetCode百钱买百鸡python递归解法示例

小结

#公鸡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:
        pythonreturn
    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递归解法的资料请关注编程客栈(www.devze.com)其它相关文章!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新开发

开发排行榜