Leetcode-39-Submission Details (Medium)
1、首先对数组进行排序
2、递归搜索符合的元素
3、注意回溯
超越67%的用户
#!/usr/local/bin/python3
# -*- coding: utf-8 -*-
__author__ = 'author'
import copy
class Solution(object):
    def __init__(self):
        self.result = []
    def combinationSum(self, candidates, target):
        """
        :type candidates: List[int]
        :type target: int
        :rtype: List[List[int]]
        """
        candidates.sort(reverse = True)
        return self.search_combinationSum(candidates, 0, [], 0, target)
    def search_combinationSum(self, candidates, index, tempRet, tempSum, target):
        #递归终止条件
        if target == tempSum:
            self.result.append(copy.deepcopy(tempRet))
            return
        elif target < tempSum:
            return
        for i in range(index, len(candidates)):
            if tempSum + candidates[i] <= target:
                tempRet.append(candidates[i])
                tempSum = tempSum + candidates[i]
                self.search_combinationSum(candidates, i, tempRet, tempSum, target)
                #回溯
                del tempRet[len(tempRet) - 1]
                tempSum = tempSum - candidates[i]
        return self.result
if __name__ == '__main__':
    s = Solution()
    print(s.combinationSum([2, 6, 3, 7], 7))
 
                    
                
 
                
            
         浙公网安备 33010602011771号
浙公网安备 33010602011771号