代码:
class Solution {public List<List<Integer>> combinationSum(int[] candidates, int target) {List<List<Integer>> res = new ArrayList<>();List<Integer> curRes = new ArrayList<>();Arrays.sort(candidates);comb(0,curRes,res,candidates,target);return res;}public void comb(int idx,List<Integer> curRes,List<List<Integer>> res, int[] candidates, int target){for(int i=idx;i<candidates.length;i++){if(target==candidates[i]){curRes.add(candidates[i]);List<Integer> cr = new ArrayList<>(curRes);res.add(cr);curRes.remove(curRes.size() - 1);}else if(target-candidates[i]>0){curRes.add(candidates[i]);comb(i,curRes,res,candidates,target-candidates[i]);if(curRes.size()>0){curRes.remove(curRes.size() - 1);}}else{if(curRes.size()>0){// curRes.remove(curRes.size() - 1);return;}}}}
}
这好像叫回溯法