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]
]
JAVA
方法一
刚开始想使用hashmap来做,但是发现题中要求组合唯一,这样一来用hashmap出来的结果一定会有重复的,那么就要进行去重操作,而我又不会做。。
所以使用递归的方式,注意边界条件以及第一次调用时需要使用循环,以便可以从任意一个下标作为起始位置,否则会丢解。本来只是用这种暴力方式来试试,没想到效率在前1/4。莫非在LeetCode中递归的效率特别高???
public class Solution {
public List<List<Integer>> combinationSum(int[] candidates, int target) {
List<List<Integer>> result = new LinkedList<List<Integer>>();
LinkedList<Integer> tempResult = new LinkedList<Integer>();
if(candidates.length != 0){
Arrays.sort(candidates);
for (int i = 0; i < candidates.length; i++) {
getResult(candidates,target,result,i,0,tempResult);
}
}
return result;
}
public void getResult(int[] candidates, int target,List<List<Integer>> result,
int currentIndex,int currentSum,LinkedList<Integer> tempResult){
currentSum += candidates[currentIndex];
tempResult.add(candidates[currentIndex]);
if(currentSum == target){
result.add((LinkedList)tempResult.clone());
}
while(currentIndex < candidates.length && currentSum + candidates[currentIndex] <= target){
getResult(candidates,target,result,currentIndex,currentSum,tempResult);
++currentIndex;
}
tempResult.removeLast();
}
}