[Lintcode]135. Combination Sum/[Leetcode]39. Combination Sum

135. Combination Sum/39. Combination Sum

  • 本题难度: Medium
  • Topic: Search & Recursion

Description

Given a set of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.

The same repeated number may be chosen from C unlimited number of times.

Example
Given candidate set [2,3,6,7] and target 7, a solution set is:

[7]
[2, 2, 3]
Notice
All numbers (including target) will be positive integers.
Elements in a combination (a1, a2, … , ak) must be in non-descending order. (ie, a1 ≤ a2 ≤ … ≤ ak).
The solution set must not contain duplicate combinations.

我的代码

class Solution:
    """
    @param candidates: A list of integers
    @param target: An integer
    @return: A list of lists of integers
    """
    def combinationSum(self, candidates, target):
        results = []
        candidates = sorted(list(set(candidates)))
        self.dfs(candidates,target,0,[],results)
        return results
        
    def dfs(self,candidates,target,index,path,results):
        if target<0:
            return 
        if target == 0:
            return results.append(path)
        for i in range(index,len(candidates)):
            self.dfs(candidates,target-candidates[i],i,path+[candidates[i]],results)

思路
DFS
终于解开了我python 全局变量这一多年来的难题。如果局部没定义就使用它全局的定义。
ps:用glob可以在局部重新定义全局变量。

猜你喜欢

转载自www.cnblogs.com/siriusli/p/10381501.html
今日推荐