组合总和 II

题目描述:给定一个数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。

candidates 中的每个数字在每个组合中只能使用一次。

说明:

  • 所有数字(包括目标数)都是正整数。
  • 解集不能包含重复的组合。

示例说明请见LeetCode官网。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/combination-sum-ii/
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

解法一:回溯算法
  • 首先,将原数组排序;
  • 然后,声明一个数组freq用来记录每个不同的数字出现的次数;
  • 然后,用回溯算法递归判断处理的序列是否符合条件,将符合条件的序列添加到结果集中,最后返回所有符合条件的结果集。
  1. import java.util.ArrayList;
  2. import java.util.Arrays;
  3. import java.util.List;
  4. public class LeetCode_040 {
  5. /**
  6. * 记录每个不同的数字出现的次数
  7. */
  8. private static List<int[]> freq = new ArrayList<>();
  9. /**
  10. * 符合条件的结果集
  11. */
  12. private static List<List<Integer>> ans = new ArrayList<>();
  13. /**
  14. * 匹配的序列
  15. */
  16. private static List<Integer> sequence = new ArrayList<>();
  17. /**
  18. * 回溯算法
  19. *
  20. * @param candidates
  21. * @param target
  22. * @return
  23. */
  24. public static List<List<Integer>> combinationSum2(int[] candidates, int target) {
  25. // 首先将给定的数组排序
  26. Arrays.sort(candidates);
  27. for (int num : candidates) {
  28. int size = freq.size();
  29. if (freq.isEmpty() || num != freq.get(size - 1)[0]) {
  30. freq.add(new int[]{num, 1});
  31. } else {
  32. ++freq.get(size - 1)[1];
  33. }
  34. }
  35. dfs(0, target);
  36. return ans;
  37. }
  38. public static void dfs(int pos, int rest) {
  39. if (rest == 0) {
  40. /**
  41. * 如果当前的和已经等于target了,将当前的序列添加到结果集
  42. */
  43. ans.add(new ArrayList<Integer>(sequence));
  44. return;
  45. }
  46. if (pos == freq.size() || rest < freq.get(pos)[0]) {
  47. /**
  48. * 如果已经遍历完所有的数字或者待处理的数小于下一个要匹配的数字,则当前的序列不符合条件,返回
  49. */
  50. return;
  51. }
  52. dfs(pos + 1, rest);
  53. int most = Math.min(rest / freq.get(pos)[0], freq.get(pos)[1]);
  54. for (int i = 1; i <= most; ++i) {
  55. sequence.add(freq.get(pos)[0]);
  56. dfs(pos + 1, rest - i * freq.get(pos)[0]);
  57. }
  58. for (int i = 1; i <= most; ++i) {
  59. sequence.remove(sequence.size() - 1);
  60. }
  61. }
  62. public static void main(String[] args) {
  63. int[] candidates = new int[]{10, 1, 2, 7, 6, 1, 5};
  64. for (List<Integer> integers : combinationSum2(candidates, 8)) {
  65. for (Integer integer : integers) {
  66. System.out.print(integer + " ");
  67. }
  68. System.out.println();
  69. }
  70. }
  71. }

【每日寄语】 登高望远,不是为了被整个世界看到,而是为了看到整个世界。