弟中弟的Leetcode总结——数组类(八)

弟中弟的Leetcode总结——数组类(八)

题目描述

Combination Sum

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

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

Note:

All numbers (including target) will be positive integers.
The solution set must not contain duplicate combinations.
Example 1:

Input: candidates = [2,3,6,7], target = 7,
A solution set is:
[
[7],
[2,2,3]
]

思路

这道题用到了DFS的思路,通过backtrack从而走遍所有的路径。
自己总结了一下要注意以下几点:
1、由于题目说了可以使用相同元素,因此递归的时候要从自己开始递归,而不是下一个元素。
2、放在templist里的元素在后面要将它pop出去。
3、使用py的时候要记得list需要浅拷贝,否则每次append的都是相同对象。
4、不要在class里定义私有属性,不然验证的时候会出错,会包含不同输入的东西。

代码(py3)

class Solution:
    def backtrack(self, pos, nums, temp, rest, ans):
        if(rest==0):
            #浅拷贝list
            temp1=temp[:]
            ans.append(temp1)
        elif(rest<0):
            return
        else:
            for i in range(pos,len(nums)):
                #将可能的元素放进templist中,然后再将所有未走的元素(包括自己放入下一步)
                temp.append(nums[i])
                self.backtrack(i,nums,temp,rest-nums[i],ans)
                #走完后记得将这个元素移除
                temp.pop()
    def combinationSum(self, candidates, target):
        """
        :type candidates: List[int]
        :type target: int
        :rtype: List[List[int]]
        """
        candidates.sort()
        temp=[]
        ans=[]
        #对第一个元素进行递归
        self.backtrack(0, candidates,temp,target,ans)
        return ans
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值