【LeetCode】39.Combination Sum(Medium)解题报告
题目地址:https://leetcode.com/problems/combination-sum/description/
题目描述:
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,
A solution set is: [ [7], [2, 2, 3]]
理解:连续四道题放到一起,每道题都有一点条件上的变化。这道题要求数字可以多次利用,不要求数字的个数。combo(res,candidates,target-candidates[i],tempList,i);这一行很重要,而且此类dfs很多模板题,要熟练。最后面if条件去重(结果中的重复list)。
Solution:
class Solution {
public List<List<Integer>> combinationSum(int[] candidates, int target) {
List<List<Integer>> res = new ArrayList<>();
List<Integer> tempList = new ArrayList<>();
Arrays.sort(candidates);
combo(res,candidates,target,tempList,0);
return res;
}
public void combo(List<List<Integer>> res,int[] candidates,int target,List<Integer> tempList,int index){
if(target<0){
return;
}else if(target==0){
res.add(new ArrayList(tempList));
}else{
for(int i=index;i<candidates.length;i++){
tempList.add(candidates[i]);
combo(res,candidates,target-candidates[i],tempList,i);
tempList.remove(tempList.size()-1);
if(i<candidates.length-1 && candidates[i]==candidates[i+1]) i++;
}
}
}
}
Date:2017年12月12日