leetcode 39. Combination Sum why do I have to return after I get one solution?

Question:

so the question is like this:

Given an array of distinct integers candidates and a target integer target, return a list of all unique combinations of candidates where the chosen numbers sum to target. You may return the combinations in any order.

The same number may be chosen from candidates an unlimited number of times. Two combinations are unique if the frequency of at least one of the chosen numbers is different.

The test cases are generated such that the number of unique combinations that sum up to target is less than 150 combinations for the given input.

Example 1:

Input: candidates = [2,3,6,7], target = 7
Output: [[2,2,3],[7]]
Explanation:
2 and 3 are candidates, and 2 + 2 + 3 = 7. Note that 2 can be used multiple times.
7 is a candidate, and 7 = 7.
These are the only two combinations.

I use backtrack ingto solve this , here is my code

class Solution:
    def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
        
        res = []
        
        def backtrack(i,cur,total):
            if total == target:
                res.append(cur[:])
            
            if i>=len(candidates) or total > target:
               return
          
            cur.append(candidates[i])
            backtrack(i, cur,total+candidates[i])
            cur.pop()
            
            backtrack(i+1,cur, total)
        
        backtrack(0,[],0)
        return res
            

At first I didn’t put return after res.append(cur[:]) so i got the woring result [[2,2,3],[2,2,3],[2,2,3],[2,2,3],[7],[7]] instead of [[2,2,3],[7]] .So I add return to fix it, but honestly I have no idea how this works, isn’t it gonna automatically hit the constrain since total already equals target? How did I get dupulicate returns?

Also I was thinking if I sort the array, for example if I get [2,6] it’s already bigger that 7 so I don’t have to iterate [2,7], or if I get [2,2,2,3], so I don’t have to go through [2,2,2,6],[2,2,,2,7] etc. I get the idea but I don’t know how to put it into code.

Asked By: sakana

||

Answers:

Just print each your steps and you will see why it works.

For example, if you don’t add return after res.append(cur[:]), what happens?

i =  1  cur =  [2, 2, 3] total =  7

Then you will add cur to res

res =  [[2, 2, 3]]

But you will go next because i = 1 < len(candidates) AND total < target.

i =  2  cur =  [2, 2, 3] total =  7

It will add one more to res.

res =  [[2, 2, 3], [2, 2, 3]]

So, you can change your code in one of following ways.

  1. Add return after add cur to res as your idea.
  2. change condition of second if to total >= target.
Answered By: GAVD