弟中弟的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