题目:
Given a set of candidate numbers (C) 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.
Elements in a combination (a1, a2, … , ak) must be in non-descending order. (ie, a1 ≤ a2 ≤ … ≤ ak).
The solution set must not contain duplicate combinations.
For example, given candidate set 2,3,6,7 and target 7,
A solution set is:
[7]
[2, 2, 3]
题目链接:https://leetcode.com/problems/combination-sum/
分析:题意给定一组数组,找出所有满足组合的元素和=targetDFS数组元素可重复使用。直接用递归求解,与之前LeetCode的3sum的有相似之处,可参考一下。
将给定数组排列之后,进行递归,用(target - candidates【i】(即当前元素))作为下次递归的target,每次的递归从0–candidates.length,当target<0直接跳出递归,target == 0时即为符合要求的组合。注意去掉重复元素产生的重复组合。
具体递归演示如图示:
Java代码 Accepted:
public class Solution {
public List<List<Integer>> combinationSum(int[] candidates, int target) {
List<Integer> subRes = new ArrayList<Integer>();
List<List<Integer>> result = new ArrayList<List<Integer>>();
//Special case
if(candidates.length == 0 || candidates == null)
return result;
//Sort array before find combination
Arrays.sort(candidates);
//Recursive DFS
recursionFunction(candidates,0,target,subRes,result);
return result;
}
public static void recursionFunction(int[] candidates,int begin,int target,List<Integer> subRes,List<List<Integer>> result){
if(target < 0)
return;
else if(target == 0){
//Have to redeclarat subRes as ArrayList<Integer> or can't get resSub
result.add(new ArrayList<Integer>(subRes));
return;
}else{
for(int i = begin;i < candidates.length;i ++){
//To eliminate repeate elment of candidates
if(i > 0 && candidates[i] == candidates[i - 1])
continue;
subRes.add(candidates[i]);
recursionFunction(candidates,i,target - candidates[i],subRes,result);
subRes.remove(subRes.size() - 1);
}
}
}
}
Python代码 Accepted
class Solution(object):
def __init__(self):
self.res = []
self.subRes = []
self.target = 0
def combinationSum(self, candidates, target):
"""
:type candidates: List[int]
:type target: int
:rtype: List[List[int]]
"""
if(len(candidates) == 0 or candidates == None):
return self.res
candidates = sorted(candidates)
self.recursionFunction(candidates,0,target,self.subRes,self.res)
return self.res
def recursionFunction(self,candidates,begin,target,subRes,res):
if(target < 0):
return
elif(target == 0):
self.res.append(self.subRes)
return
else:
for i in range(begin,len(candidates)):
if(i > 0 and candidates[i] == candidates[i - 1]):
continue
self.subRes.append(candidates[i])
self.recursionFunction(candidates,i,target - candidates[i],self.subRes,self.res)
self.subRes = self.subRes[:-1]