看板 Python 關於我們 聯絡資訊
https://repl.it/IcKq/0 # comment included 不習慣 DP/遞迴 的話可以先寫迴圈版,畫個二元樹出來會比較好思考。 原題目如果沒有條件限制 " 位置不同視為相同 " ([1, 2] == [2, 1]) 的話, combo(number) 就是 DP 解了。 combos 的 recursive calls: # i in [1, 2] if n = 3 calls: combos(3-i, i) = combo(2, 1) = [[2], [1, 1]] recursive call when n = 2 ((i in [1] combo(2-i, i) = combo(1, 1) = [[1]] combos(3-i, i) = combo(1, 2) = [] # skipped because m=2 > n=1 ※ 引述《ptt0720 (濕濕)》之銘言: : def combos(n, m = 1): : if n < m: : return [] : res = [[n]] : for i in range(m, n): : l = [i] : for j in combos(n - i, i): : res += [l + j] : return res : print (combos(5)) : 我寫題目遇到一題 題目是這樣 : 假如輸入3 要列出所有相加等於3的情況 : [3],[2,1],[1,1,1] : 然後爬文看到一個算式比較簡單的寫法 : 但是還是不太懂 : 第七行為什麼可以讓迴圈在def執行? : 還有他的每一層迭代我也不是很了解 : 目前只理解到 第一次執行會留下自己的值 : 接下來把自己的值-1 (ex:3-1=2) 繼續分解2 : 假如輸入是5呢 : [5],[1,4],[1,1,3],[1,1,1,2],[1,1,1,1,1] : 接下來的 : [1,2,2],[2,3]是如何進行迭代的 我就不太清楚了 : 希望板上神人們可以指導一下 -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 192.19.253.250 ※ 文章網址: https://www.ptt.cc/bbs/Python/M.1496917364.A.345.html ※ 編輯: zerof (192.19.253.250), 06/08/2017 18:24:40
ides13: 推 06/09 09:16