您好,欢迎来到花图问答。
搜索
您的当前位置:首页组合相加

组合相加

来源:花图问答

题目

Given a set of candidate numbers (C) (without duplicates) 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.

Note:
All numbers (including target) will be positive integers.
The solution set must not contain duplicate combinations.
For example, given candidate set [2, 3, 6, 7] and target 7,

python

class Solution(object):
    def combinationSum(self, candidates, target):
        """
        :type candidates: List[int]
        :type target: int
        :rtype: List[List[int]]
        """
        result=[]
        candidates.sort();
        self.dfs(candidates,target,0,[],result)
        return result
        
    def dfs(self, nums, target, depth, path, res):
        if target < 0:
            return;
        if target == 0:
            res.append(path)
            return
        for i in range(depth, len(nums)):
            self.dfs(nums, target - nums[i], i, path + [nums[i]], res)

解题思路

深度优先遍历

Copyright © 2019- huatuowenda.com 版权所有 湘ICP备2023022495号-1

违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务