Why does the order of the iteration loop matter here?
def change1(self, amount, coins):
"""
:type amount: int
:type coins: List[int]
:rtype: int
"""
if amount == 0:
return 1
dp = [0 for _ in range(amount + 1)]
dp[0] = 1
# dp[i] to denote the number of ways to sum up to amount i.
for j in range(len(coins)): # switch those 2 statements would be wrong answer why???
for i in range(1, amount + 1):
if i - coins[j] >= 0:
dp[i] += dp[i - coins[j]]
return dp[amount]
def change2(amount, coins): # wrong answer
"""
:type amount: int
:type coins: List[int]
:rtype: int
"""
if amount == 0:
return 1
dp = [0 for _ in range(amount + 1)]
## when amount is 0, # combinations is 1
dp[0] = 1
# dp[i] to denote the number of ways to sum up to amount i.
for i in range(1, amount + 1):
for j in range(len(coins)): # switch those 2 statements would be wrong answer why???
if i - coins[j] >= 0:
dp[i] += dp[i - coins[j]]
return dp[amount]
change 1
dp[i-1] = dp[i-1-c2] + dp[i-1-c2] + dp[i-2-c2] + ..dp[0]
dp[i] = dp[i-c1] + dp[i-1-c1] + dp[i-2-c1] + ...dp[0]
This is correct solution.
change 2
dp[i-1] = dp[i-1-c1] + dp[i-1-c2] + dp[i-1-c3] + dp[i-1-c4] + ... dp[0]
dp[i] = dp[i-c1] + dp[i-c2] + dp[i-c3] + dp[i-c4] + ... dp[0]
Why this approach is WRONG?
Total amount i
can be derived from a summation of choices from taking coin c1
or c2
or c3
, this is more intuitive in my opinion.
I've checked a few references but couldn't find a satisfying answer.
EDIT: I also understand changing the order of nested loop will give wrong answer, I'm trying to understand why the 2nd approach has the wrong intuition while the 1st is correct.
Coin Change: number of solutions when order matters vs. when order doesn't matter