0

Here is the answer for LeetCode 39 problem, and I found it on github.

class Solution(object):
def combinationSum(self, candidates, target):

    self.resList = []
    candidates = sorted(candidates)
    self.dfs(candidates, [], target, 0)
    return self.resList

def dfs(self, candidates, sublist, target, last):
    if target == 0:
        // Change this line
        self.resList.append(sublist[:])
    if target < candidates[0]:
        return
    for n in candidates:
        if n > target:
            return
        if n < last:
            continue
        sublist.append(n)
        self.dfs(candidates, sublist, target - n, n)
        sublist.pop()

myClass = Solution()
result = myClass.combinationSum([2, 3, 5], 8)
print(result)

For this situation, the output is correct.

[[2, 2, 2, 2], [2, 3, 3], [3, 5]]

But if I change

...
self.resList.append(sublist[:])
...

to this

...
self.resList.append(sublist)
...

The output will be

[[], [], []]

I have no idea what's the different with "sublist" and "sublist[:]" here??

Ricky Parker
  • 133
  • 2
  • 8
  • 1
    The slicing operation ([;]) creates a shallow copy of the list, and appends a reference to the shallow copy to resList. When you remove the slicing operation, you are appending a view / reference of the original list, and any changes you make to that list will be reflected in resList. – Paul M. Nov 13 '19 at 16:43

1 Answers1

0

When you type:

self.resList.append(sublist[:])

Python is creating a new list object and appending a reference of the new list to resList.

Alternatively, when you type:

self.resList.append(sublist)

Python does not create a new list and only appends a reference to sublist, so any changes that you make to sublist in the future will show in resList.

A clearer way to code this would be:

self.resList.append(list(sublist))
big_bad_bison
  • 1,021
  • 1
  • 7
  • 12
  • 1
    The first appends a reference as well; it's just a reference to a *different* list, and one which is *only* referenced by `append`'s formal parameter. – chepner Nov 13 '19 at 16:43