List<List<Integer>> res = new ArrayList<>(); //重要的要大小排列 Arrays.sort(candidates); //说明原数组中就没有满足target的数 if (candidates[0] > target) { return res; }
List<Integer> newCandidates= new ArrayList<Integer>(); int len = candidates.length; // 取小于target的数 组成一个临时数组 for (int i = 0; i < len; i++) { int num = candidates[i]; if (num > target) { break; } newCandidates.add(num); } // end for
class Solution { public List<List<Integer>> combinationSum(int[] candidates, int target) { List<List<Integer>> res = new ArrayList<>(); //重要的要大小排列 Arrays.sort(candidates); List<Integer> temp = new ArrayList<Integer>();
if (candidates[0] > target) { return res; }
int len = candidates.length; // 取小于target的数 足证一个临时数组 for (int i = 0; i < len; i++) { int num = candidates[i]; if (num > target) { break; }
temp.add(num); } // end for // find(res, new ArrayList<>(), temp, target, 0); return res; } public void find(List<List<Integer>> res, List<Integer> tmp, List<Integer> candidates, int target, int start){ //target==0.找到一个新的解 if (target == 0) { res.add(new ArrayList<>(tmp)); }else if(target>0){ for (int i = start; i < candidates.size(); i++) { int num = candidates.get(i); if(num<=target){ tmp.add(num); //查找新的target int newTarget = target-num; find(res, tmp, candidates, newTarget, i); tmp.remove(tmp.size() - 1); } }//end for } } }