题意:求一个数组中的组合为某个target的所有子数组组合,要求不重复,
思路:先将数组排序,然后按深度遍历的思想对i - > len -1的元素进行遍历
代码如下:
思路:先将数组排序,然后按深度遍历的思想对i - > len -1的元素进行遍历
代码如下:
public class Solution {
public List<List<Integer>> combinationSum(int[] candidates, int target) {
List<List<Integer>> results = new LinkedList<List<Integer>>();
if(candidates == null || candidates.length ==0)return results;
Arrays.sort(candidates);//先来排个序
List<Integer> temp = new LinkedList<Integer>();
for(int i =0; i< candidates.length; ++i)
search(candidates, i, 0, target, results, temp);
return results;
}
/**
* 搜索函数
* @param cadidates
* @param i
* @param sum
* @param target
* @param results
* @param rs
*/
public void search(int [] cadidates, int i, int sum, int target, List<List<Integer>> results, List<Integer> rs){
if(i >= cadidates.length || sum > target) return;
else {
sum += cadidates[i];
rs.add(cadidates[i]);
if(sum == target){
List<Integer> t = new LinkedList<Integer>();
t.addAll(rs);
results.add(t);
}else if(sum > target){
}else {
for(int j = i ; j < cadidates.length; ++j)
search(cadidates, j, sum, target, results, rs);
}
rs.remove(rs.size()-1);
}
}
}