首页 > 其他 > 详细

Leetcode-39-Submission Details (Medium)

时间:2017-01-16 20:00:51      阅读:196      评论:0      收藏:0      [点我收藏+]

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))

  

Leetcode-39-Submission Details (Medium)

原文:http://www.cnblogs.com/doudouyoutang/p/6290664.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!