My code:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Solution {
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
ArrayList<List<Integer>> result = new ArrayList<List<Integer>>();
if (candidates == null || candidates.length == 0)
return result;
Arrays.sort(candidates);
ArrayList<Integer> combinations = new ArrayList<Integer>();
if (candidates[0] > target)
return result;
else if (candidates[0] == target) {
combinations.add(candidates[0]);
result.add(combinations);
return result;
}
boolean[] isVisited = new boolean[candidates.length];
getCombinations(0, 0, candidates, target, isVisited, combinations, result);
return result;
}
private void getCombinations(int begin, int sum, int[] candidates, int target, boolean[] isVisited,
ArrayList<Integer> combinations, ArrayList<List<Integer>> result) {
for (int i = begin; i < candidates.length; i++) {
int temp = candidates[i] + sum;
if (temp > target)
break;
else if (temp == target) {
combinations.add(candidates[i]);
result.add(new ArrayList<Integer>(combinations));
combinations.remove(combinations.size() - 1);
break;
}
else {
isVisited[i] = true;
if ( i >= 1 && candidates[i] == candidates[i - 1] && !isVisited[i - 1]) {
isVisited[i] = false;
continue;
}
combinations.add(candidates[i]);
getCombinations(i + 1, temp, candidates, target, isVisited, combinations, result);
combinations.remove(combinations.size() - 1);
isVisited[i] = false;
}
}
}
}
My test result:
这道题目和之前的差不多,唯一的不同就是,只能用一次了,那么,就传递 i + 1就行了。
但是还需要考虑一个问题, candidates[] 数组中的元素是会有重复的,导致最后的结果也有重复,所以需要采用措施把这个重复情况排除掉,这个也是清楚怎么做的。
**
总结: Array, DFS
**
Anyway, Good luck, Richardo!
My code:
public class Solution {
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
ArrayList<List<Integer>> ret = new ArrayList<List<Integer>>();
if (candidates == null || candidates.length == 0 || target < 0)
return ret;
Arrays.sort(candidates);
ArrayList<Integer> group = new ArrayList<Integer>();
helper(0, 0, target, candidates, ret, group);
return ret;
}
private void helper(int begin, int sum, int target, int[] candidates,
ArrayList<List<Integer>> ret, ArrayList<Integer> group) {
if (sum > target)
return;
else if (sum == target) {
ret.add(new ArrayList<Integer>(group));
return;
}
else {
for (int i = begin; i < candidates.length; i++) {
if (i > begin && candidates[i] == candidates[i - 1]) // in order to prevent repeating situation
// such as, [1, 1] for 1
continue;
group.add(candidates[i]);
helper(i + 1, sum + candidates[i], target, candidates, ret, group);
group.remove(group.size() - 1);
}
}
}
}
没能一遍过,一个地方错了。
就是这里是不允许重复的。
那么,如果[1, 1] for 1, 答案只能是一个[1].
所以需要加一个判断避免重复对相同情况DFS
Anyway, Good luck, Richardo!