- 思路一
- 这道题最初的想法是一开始我们寻找组合时都选择在函数中传一个索引index来表明到底选择哪一个元素。但是这道题可以重复选,所以选择在helper函数中用for循环的方式来遍历取值。但是这样可能会产生重复值,比如[2,3,6,7],7。可能会产生[2,2,3],[2,3,2]这样同样的结果。因此需要用一个set来存储结果
class Solution { Set<List<Integer>> result; int[] candidates; int target; public List<List<Integer>> combinationSum(int[] candidates, int target) { result = new HashSet<>(); this.candidates = candidates; this.target = target; helper(new ArrayList<>(), 0); return result.stream().toList(); } private void helper(List<Integer> combination, int sum) { if (sum == target) { List<Integer> tmp = new ArrayList<>(combination); Collections.sort(tmp); result.add(tmp); } else if (sum > target) return; for (int num : candidates) { combination.add(num); helper(combination, sum + num); combination.remove(combination.size() - 1); } } }
- 思路二:可以重复选值并不代表不能用index来表明当前是对哪一个元素做选择
- 我们依旧可以用一个index来表示此时在纠结哪一个元素,如果不选择这个元素,那么我们就helper(index + 1),如果选择了这个元素,我们仍然需要helper(index),因为是可以重复选择的!
// 不选择本次索引的元素 helper(combination, sum, index + 1); // 选择本次索引的元素 combination.add(candidates[index]); helper(combination, sum + candidates[index], index); combination.remove(combination.size() - 1);
- 有趣的是这样写也有效的避免了重复答案的问题,会看当初,为何会产生[2,2,3],[2,3,2]这样相同的结果,就是因为对于某一次关于某一个数字的选择,可以从头开始。比如第一次选择了2,那么第二次可以选择2也可以选择3,那么此时就有了[2,2]和[2,3],第三次选择对于第一种情况,可以继续选择2、3、6、7,对于第二种情况仍然可以选择2、3、6、7,重复就是这样产生的
- 但是对于我们这种写法,index是递增的,也就是随着树的深入,可选择的数字越来越少且不能再选择前面的,所以就不会出现232这种情况了,自然也就不存在重复的可能~
class Solution { List<List<Integer>> result; int[] candidates; int target; public List<List<Integer>> combinationSum(int[] candidates, int target) { result = new ArrayList<>(); this.candidates = candidates; this.target = target; helper(new ArrayList<>(), 0, 0); return result; } private void helper(List<Integer> combination, int sum, int index) { if (sum == target) { result.add(new ArrayList<>(combination)); return; } else if (sum > target) return; if (index < candidates.length) { // 不选择本次索引的元素 helper(combination, sum, index + 1); // 选择本次索引的元素 combination.add(candidates[index]); helper(combination, sum + candidates[index], index); combination.remove(combination.size() - 1); } } }
剑指offer 专项突破版 81、允许重复选择元素的组合
最新推荐文章于 2023-06-17 00:17:39 发布