Conversation
| if i + coin > amount: | ||
| continue | ||
| if min_coins_to_amount[i + coin] == -1 or \ | ||
| min_coins_to_amount[i + coin] > num_coins + 1: |
There was a problem hiding this comment.
この条件分岐の方法は思いつきませんでした。minなどの比較をしなくてよくなるのでシンプルになっていいですね!
There was a problem hiding this comment.
min_coins_to_amount の値を大きな数字で初期化すれば、 if 文が不要になると思います。
INFINITY = 100000
min_coins_to_amount = [0] + [INFINITY] * amount
for i, num_coins in enumerate(min_coins_to_amount):
if num_coins == -1:
continue
for coin in coins:
if i + coin > amount:
continue
min_coins_to_amount[i + coin] = min(min_coins_to_amount[i + coin], num_coins + 1)
if min_coins_to_amount[-1] == INFINITY:
return -1
return min_coins_to_amount[-1]There was a problem hiding this comment.
確かに最後に一回分岐作るだけの方が良さそうですね
| if amount < 0: | ||
| continue | ||
| if amount == 0: | ||
| return 0 |
| ```python | ||
| class Solution: | ||
| def coinChange(self, coins: List[int], amount: int) -> int: | ||
| remaining_to_min_coin = [None] * amount + [0] |
There was a problem hiding this comment.
同一の list の中に、 None と 0 という異なる型の値が含まれている点に違和感を感じました。
There was a problem hiding this comment.
そうなんですね、同じ型で比較できる形の方が自然なんですね
There was a problem hiding this comment.
remaining_to_min_coin = [None] * (amount + 1)
remaining_to_min_coin[amount] = 0の方が
一気に違う型を入れて初期化するよりは違和感は少ないかもしれません
| min_coins = \ | ||
| min(min_coins, numCoinsToAmount(amount - coin) + 1) | ||
| return min_coins | ||
| num_coins = numCoinsToAmount(amount) |
There was a problem hiding this comment.
関数の切れ目が認識しづらいため、個人的には inner function のあとに空行を入れたいです。
| if i + coin > amount: | ||
| continue | ||
| if min_coins_to_amount[i + coin] == -1 or \ | ||
| min_coins_to_amount[i + coin] > num_coins + 1: |
There was a problem hiding this comment.
min_coins_to_amount の値を大きな数字で初期化すれば、 if 文が不要になると思います。
INFINITY = 100000
min_coins_to_amount = [0] + [INFINITY] * amount
for i, num_coins in enumerate(min_coins_to_amount):
if num_coins == -1:
continue
for coin in coins:
if i + coin > amount:
continue
min_coins_to_amount[i + coin] = min(min_coins_to_amount[i + coin], num_coins + 1)
if min_coins_to_amount[-1] == INFINITY:
return -1
return min_coins_to_amount[-1]| if remaining_to_min_coin[remaining] is None: continue | ||
| for coin in coins: | ||
| if coin > remaining: continue | ||
| for i in range(remaining // coin, 0, -1): |
| class Solution: | ||
| def coinChange(self, coins: List[int], amount: int) -> int: | ||
| @cache | ||
| def numCoinsToAmount(amount: int) -> int: |
There was a problem hiding this comment.
https://google.github.io/styleguide/pyguide.html#316-naming
LeetCodeは何故か従ってないのですが、Pythonの関数名はnum_coins_to_amountのような表記が一般的そうです。
チームのルールによって異なるとは思います。
問題文:https://leetcode.com/problems/coin-change/description/