本文共 1477 字,大约阅读时间需要 4 分钟。
为了解决这个问题,我们需要找到所有可以组合起来的数字,使得它们的和等于目标数,并且每个数字只能在组合中使用一次。我们将使用深度优先搜索(DFS)来遍历所有可能的组合,同时确保生成的组合是唯一的。
import java.util.ArrayList;import java.util.Arrays;import java.util.HashSet;import java.util.List;import java.util.Set;import java.util.Stack;public class Solution { List
> res = new ArrayList<>(); Set set = new HashSet<>(); public List
> combinationSum2(int[] candidates, int target) { Arrays.sort(candidates); recursion(candidates, target, 0, 0, new Stack<>(), ""); return res; } private void recursion(int[] candidates, int target, int pos, int cur, Stack stack, String rec) { if (cur == target) { if (!set.contains(rec)) { set.add(rec); res.add(new ArrayList<>(stack)); } return; } if (pos == candidates.length) return; for (int i = pos; i < candidates.length; i++) { int num = candidates[i]; if (cur + num > target) break; stack.add(num); recursion(candidates, target, i + 1, cur + num, stack, rec + num); stack.pop(); } }}
Arrays.sort
对候选数组进行排序。recursion
函数用于深度优先搜索,参数包括当前位置pos
、当前和cur
、路径栈stack
、当前路径字符串rec
。cur
加上当前数字超过目标数,就break递归,避免无效路径。这种方法确保了所有可能的组合都被探索,并且通过排序和字符串去重,避免了重复组合的生成。
转载地址:http://tjgr.baihongyu.com/