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
參考:## 狀態(tài)轉(zhuǎn)移解法(遞歸)
# (公雞數(shù),母雞數(shù),小雞數(shù),總錢數(shù),總雞數(shù)),狀態(tài)轉(zhuǎn)移 import numpy as np # 導(dǎo)入numpy庫 st = np.zeros((100, 100, 100)) # 新建三維數(shù)組,且初始值為0,記錄狀態(tài)是否被遍歷過,進(jìn)行剪枝操作 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) # (公雞數(shù),母雞數(shù),小雞數(shù),總錢數(shù),總雞數(shù)) resolve(0, 0, 0, 0, 0)
## 運(yùn)行結(jié)果
小結(jié)
#公雞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遞歸解法示例的詳細(xì)內(nèi)容,更多關(guān)于百錢買百雞python遞歸解法的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Python實(shí)現(xiàn)程序的單一實(shí)例用法分析
這篇文章主要介紹了Python實(shí)現(xiàn)程序的單一實(shí)例用法,較為詳細(xì)的分析了Python窗口的相關(guān)操作技巧,需要的朋友可以參考下2015-06-06Python通過兩個dataframe用for循環(huán)求笛卡爾積
這篇文章主要介紹了Python通過兩個dataframe用for循環(huán)求笛卡爾積,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2020-04-04Tensorflow 多線程與多進(jìn)程數(shù)據(jù)加載實(shí)例
今天小編就為大家分享一篇Tensorflow 多線程與多進(jìn)程數(shù)據(jù)加載實(shí)例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-02-02python使用pynput捕獲單個按鍵的步驟詳解(包括組合鍵和功能鍵)
在數(shù)字時代,鍵盤是與計算機(jī)交流的主要工具,鍵盤的每一次敲擊都承載著信息,而在某些場景下,可能需要記錄這些信息,這時候,pynput庫就派上了大用場,它可以輕松地幫捕獲并記錄鍵盤上的每一個操作,所以本文給大家介紹了python使用pynput捕獲鍵的操作步驟2024-05-05詳解python的webrtc庫實(shí)現(xiàn)語音端點(diǎn)檢測
這篇文章主要介紹了詳解python的webrtc庫實(shí)現(xiàn)語音端點(diǎn)檢測,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-05-05Django框架模板語言實(shí)例小結(jié)【變量,標(biāo)簽,過濾器,繼承,html轉(zhuǎn)義】
這篇文章主要介紹了Django框架模板語言,結(jié)合實(shí)例形式總結(jié)分析了Django框架中變量,標(biāo)簽,過濾器,繼承,html轉(zhuǎn)義等相關(guān)模板語言操作技巧,需要的朋友可以參考下2019-05-05