题目描述:
简单点来说就是给你一个不包含重复元素的数组candidates和一个目标值 target,让你在candidates数组中找出所有相加能组合成目标值target的组合,但不允许结果重复如[2,3,3]和[3,3,2]应该算是一个结果。
解法分析:
我的思路是首先数组candidates一定要带顺序,然后从大到小来寻找组合。循环遍历当数组中的值x比目标值小的时候,可以进行基于x的组合子查找,查找方法就是改变目标值为target-x和一个最大值限制x,这样基于x的组合查找就不会去组合比x更大的值,防止了重复组合问题的发生。如果基于x的子查找有返回结果,那么在每个返回结果组合中加入x即是本次遍历中的一个结果,没有则返回空数组。代码如下:
class Solution {
public List<List<Integer>> combinationSum(int[] candidates, int target) {
Arrays.sort(candidates);
return combinationSum(candidates, target, candidates[candidates.length - 1]);
}
public List<List<Integer>> combinationSum(int[] candidates, int target, int max) {
List<List<Integer>> result = new ArrayList<List<Integer>>();
for (int i = 0; i < candidates.length; i++) {
if (candidates[i] > max) {
break;
} else if (candidates[i] == target) {
List<Integer> tmp = new ArrayList<Integer>();
tmp.add(candidates[i]);
result.add(tmp);
} else if (candidates[i] < target) {
List<List<Integer>> tmpResult = combinationSum(candidates, target - candidates[i], candidates[i]);
for (List<Integer> list : tmpResult) {
list.add(candidates[i]);
result.add(list);
}
}
}
return result;
}
}