Home > Back-end >  Why do I have to set curSum before passing it in as a parameter?
Why do I have to set curSum before passing it in as a parameter?

Time:10-03

I'm solving Coin Change II on Leetcode and ran into a question:

I get the wrong answer if I pass in curSum coins[i] as a parameter into the recursive dfs call, but get the right answer if I set curSum = coins[i] and then pass curSum into the dfs function.

Here's the code. This gives me the wrong solution: (test case: target = 5, coins[1,2,5] yields ans: 6 (should be 4))

class Solution:
    def change(self, target: int, coins: List[int]) -> int:
        self.res = 0
        def dfs(i, curSum):
            if curSum == target:
                self.res  = 1
                return
            if i == len(coins) or curSum > target:
                return
            
            dfs(i, curSum coins[i])
            dfs(i 1, curSum-coins[i])
        dfs(0,0)
        return self.res

but this gives me the right answer(test case: target = 5, coins[1,2,5] yields ans: 4 (should be 4)):

class Solution:
    def change(self, target: int, coins: List[int]) -> int:
        self.res = 0
        def dfs(i, curSum):
            if curSum == target:
                self.res  = 1
                return
            if i == len(coins) or curSum > target:
                return
            
            curSum  = coins[i]
            dfs(i, curSum)
            curSum -= coins[i] 
            dfs(i 1, curSum)
        dfs(0,0)
        return self.res           

I'm ultimately passing in the same value, right? Why do the two codepieces behave differently?

CodePudding user response:

Looking at the 2 different versions, and adding what value is acually passed to dfs(), assuming curSum=1 and coins[i]=2:

            dfs(i, curSum coins[i])    # 1 2 = 3
            dfs(i 1, curSum-coins[i])  # 1-2 = -1

and

            curSum  = coins[i]    # curSum = 1 2 (= 3)
            dfs(i, curSum)        # passed `3`
            curSum -= coins[i]    # curSum = 3-2 (= 1)
            dfs(i 1, curSum)      # passed `1` (instead of `-1`, above)

In the second instance, curSum is updated by each -= or =.

When in doubt, add an (e.g.) print(f'function call: dfs({i}, {curSum})') at the top of dfs()

  • Related