混淆在python的递归函数中传递列表

时间:2018-04-11 11:30:01

标签: python

class Solution(object):
def combinationSum2(self, candidates, target):
    """
    :type candidates: List[int]
    :type target: int
    :rtype: List[List[int]]
    """
    candidates.sort()
    res = []  # save the result
    path = []  # save each unique combination
    self.dfs(0, target, path, res, candidates)
    return res

def dfs(self, start_index, target, path, res, candidates):
    if target == 0:
        res.append(path)
        return
    if target < 0:
        path.pop()
        return
    for i in range(start_index, len(candidates)):
        if i > start_index and candidates[i] == candidates[i-1]:
            continue
        path += [candidates[i]]
        self.dfs(i+1, target-candidates[i], path, res, candidates)
        if path:
            path.pop()

上面的LeetCode问题组合Sum II 的代码,给定输入[10,1,2,7,6,1,5]8,输出应为[[1,1,6],[1,2,5],[1,7],[2,6]]。但是,这段代码的输出运行为[[],[],[],[]],我很困惑,并且想知道原因:(

0 个答案:

没有答案