此次和上次的区别是元素不能重复使用了,这也简单,每一次去掉使用过的元素便可。java
经过分析咱们能够知道使用递归就能够解决问题,而且此次咱们从头遍历一次就不会出现屡次使用某一个元素了。spa
class Solution { List<List<Integer>> ans; public List<List<Integer>> combinationSum2(int[] candidates, int target) { Arrays.sort(candidates); ans = new ArrayList<>(); track(candidates, 0, target, new ArrayList<>()); return ans; } private void track(int[] candidates, int index, int target, List<Integer> list) { if (target == 0) { ans.add(list); return; } for (int i = index; i < candidates.length; i++) { if (target < candidates[i] || (i > index && candidates[i] == candidates[i - 1]))//重要
continue; List<Integer> temp = new ArrayList<>(list); temp.add(candidates[i]); track(candidates, i + 1, target - candidates[i], temp); } } }
若是这里没有(i > index && candidates[i] == candidates[i - 1])判断的话,就会形成重复的结果,究其缘由是若是两个相同,以前的添加以后会进入到下一个递归里面运行了,而咱们这个时候若是不过滤再次运行就会重复。blog
递归在咱们的程序中用的很是多,必定要熟练深入掌握。递归