leetcode 39. Combination Sum | 39. 组合总和(Java)

ゝ一世哀愁。 2022-09-03 07:28 264阅读 0赞

题目

https://leetcode.com/problems/combination-sum/
在这里插入图片描述

题解

不是最优解法。

对于每一个位置 i 上 的元素,分为选或不选两种情况。
遍历每一个位置,计算强制选择当前元素的情况下,后面的元素怎么处理。
因为每一个元素都被强制选过,所以不会有遗漏。

  1. class Solution {
  2. Set<List<Integer>> set;
  3. public List<List<Integer>> combinationSum(int[] arr, int target) {
  4. Arrays.sort(arr);
  5. set = new HashSet<>();
  6. for (int i = 0; i < arr.length; i++) {
  7. List<Integer> list = new ArrayList<>();
  8. list.add(arr[i]);
  9. process(list, i, arr, target - arr[i]); // 强制加入i位置元素
  10. }
  11. return new ArrayList<>(set);
  12. }
  13. public void process(List<Integer> list, int i, int[] arr, int target) {
  14. List<Integer> newList;
  15. if (target == 0) {
  16. newList = new ArrayList<>(list);
  17. set.add(newList);
  18. } else if (target > 0) {
  19. for (int j = i; j < arr.length; j++) { // 不用管前面,前面已经保证过了
  20. newList = new ArrayList<>(list);
  21. newList.add(arr[j]);
  22. process(newList, j, arr, target - arr[j]);
  23. }
  24. }
  25. }
  26. }

在这里插入图片描述

发表评论

表情:
评论列表 (有 0 条评论,264人围观)

还没有评论,来说两句吧...

相关阅读

    相关 leetcode:39.组合总和

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