Create 322. Coin Change.md#40
Conversation
| if amount < 0: | ||
| return -1 | ||
|
|
||
| def possible_coin(): |
There was a problem hiding this comment.
レビューありがとうございます。
if (num_coins := coin_change_helper(amount - coin)) == -1:
continue
yield num_coins + 1セイウチだとこういう感じですね。
There was a problem hiding this comment.
想定はこんな感じです。
(num_coins + 1 for coin in coins if (num_coins := coin_change_helper(coin)) != -1)
| if amount == 0: | ||
| return 0 | ||
| if amount < 0: | ||
| return -1 |
There was a problem hiding this comment.
好みの範囲だと思いますが、amountの大きさの順番で処理がなされる方が自然な気がします。
if amount < 0:
~~~~
if amount == 0:
~~~~
# amount > 0の時の処理There was a problem hiding this comment.
レビューありがとうございます!
その視点はありませんでした!
| return 0 | ||
| possible_amounts = [0] | ||
| num_coin = 0 | ||
| checked = set() |
There was a problem hiding this comment.
処理には影響しませんが、checked.add()のタイミング的に、ここでchecked = set([0])としたくなります。
| continue | ||
| yield num_coins + 1 | ||
|
|
||
| return min(possible_coin(), default=-1) |
There was a problem hiding this comment.
possible_coin関数は内部でcoin_change_helper関数を呼び、coin_change_helper関数は内部でpossible_coin関数を呼ぶ、という依存関係は認知負荷が高いように感じました。
There was a problem hiding this comment.
レビューありがとうございます。
確かに私も最初は読みにくいと感じました。
二つの関数で再帰していくという感じですね。
|
|
||
| def possible_coin(): | ||
| for coin in coins: | ||
| num_coins = coin_change_helper(amount - coin) |
There was a problem hiding this comment.
好みの問題かと思いますが、私はnum_coins = coin_change_helper(amount - coin) + 1としたくなります。
There was a problem hiding this comment.
考えましたが、-1のケースに足すのに抵抗があったのでこの書き方にしました。
|
|
||
| 総当たり | ||
|
|
||
| 総当たりは最大100^12くらい行きそうなので無理そう。 |
There was a problem hiding this comment.
ざっくり最も時間がかかりそうなケースで、
amount が10^4程度で、coinの枚数が12枚、コインの値が1~12の時は、10^4 / 12 = 100で、それが12個あるから12を累乗しました。
今考えると、もっと計算量がかかりそうだと思いました。
Constraints:
1 <= coins.length <= 12
1 <= coins[i] <= 2^31 - 1
0 <= amount <= 10^4
There was a problem hiding this comment.
10^4 / 12 = 100
833 くらいではないでしょうか。
自分なら
amount = 10^4
coins = [1, 2, ..., 12]
として、ある金額から 12 通りの分岐があるため、 10000^12 または数桁小さいと見積もると思います。
There was a problem hiding this comment.
ありがとうございます。
無理だろうなと思って結論ありきで計算していたので間違いに気づけませんでした。
https://leetcode.com/problems/coin-change/description/