组合总和

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

candidates 中的数字可以无限制重复被选取。

说明:

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

示例说明请见LeetCode官网。

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

解法一:穷举法

类似构造一棵多叉树,最大深度为candidates数组的长度,然后获取所有可能的路径,最大路径是由根节点到叶子节点,判断所有的路径之和是否等于target,如果相等,则加到结果集中,最后需要判重,把重复的组合去掉,最后返回。

  1. import java.util.*;
  2. public class LeetCode_039 {
  3. /**
  4. * 穷举法
  5. *
  6. * @param candidates
  7. * @param target
  8. * @return
  9. */
  10. public static List<List<Integer>> combinationSum(int[] candidates, int target) {
  11. // 结果集
  12. List<List<Integer>> result = new ArrayList<>();
  13. // 所有可能的组合情况
  14. Queue<List<Integer>> allPossibleCombinations = new LinkedList<>();
  15. // 初始化所有的情况
  16. for (int candidate : candidates) {
  17. List<Integer> onePossibleCombination = new ArrayList<>();
  18. onePossibleCombination.add(candidate);
  19. allPossibleCombinations.add(onePossibleCombination);
  20. }
  21. while (!allPossibleCombinations.isEmpty()) {
  22. List<Integer> temp = allPossibleCombinations.poll();
  23. int sum = 0;
  24. for (Integer num : temp) {
  25. sum += num;
  26. }
  27. if (sum == target) {
  28. result.add(temp);
  29. } else if (sum < target) {
  30. for (int candidate : candidates) {
  31. // List复制方法
  32. List<Integer> toAdd = new ArrayList<>(Arrays.asList(new Integer[temp.size()]));
  33. Collections.copy(toAdd, temp);
  34. toAdd.add(candidate);
  35. allPossibleCombinations.add(toAdd);
  36. }
  37. }
  38. }
  39. // 去重后的结果
  40. List<List<Integer>> result1 = new ArrayList<>();
  41. for (int i = 0; i < result.size(); i++) {
  42. boolean isRepeated = false;
  43. List<Integer> one = result.get(i);
  44. Collections.sort(one);
  45. for (int j = i + 1; j < result.size(); j++) {
  46. List<Integer> two = result.get(j);
  47. Collections.sort(two);
  48. if (one.size() != two.size()) {
  49. continue;
  50. }
  51. boolean equals = true;
  52. for (int x = 0; x < one.size(); x++) {
  53. if (!one.get(x).equals(two.get(x))) {
  54. equals = false;
  55. continue;
  56. }
  57. }
  58. if (equals) {
  59. isRepeated = true;
  60. }
  61. }
  62. if (!isRepeated) {
  63. result1.add(one);
  64. }
  65. }
  66. return result1;
  67. }
  68. public static void main(String[] args) {
  69. int[] candidates = new int[]{8, 10, 6, 3, 4, 12, 11, 5, 9};
  70. for (List<Integer> integers : combinationSum(candidates, 28)) {
  71. for (Integer integer : integers) {
  72. System.out.print(integer + " ");
  73. }
  74. System.out.println();
  75. }
  76. }
  77. }

【每日寄语】 不要急着让生活给予所有的答案,有时我们需要耐心的等待。相信过程,坦然前行,不负生活,生活也必不负你。