【Leetcode】39. Combination Sum

╰+攻爆jí腚メ 2022-03-09 05:08 306阅读 0赞

Given a set of candidate numbers (candidates) (without duplicates) and a target number (target), find all unique combinations in candidates where the candidate numbers sums to target.

The same repeated number may be chosen from candidates unlimited number of times.

Note:

  • All numbers (including target) will be positive integers.
  • The solution set must not contain duplicate combinations.

Example 1:

  1. Input: candidates = [2,3,6,7], target = 7,
  2. A solution set is:
  3. [
  4. [7],
  5. [2,2,3]
  6. ]

Example 2:

  1. Input: candidates = [2,3,5], target = 8,
  2. A solution set is:
  3. [
  4. [2,2,2,2],
  5. [2,3,3],
  6. [3,5]
  7. ]

题目大意:

从给出的数组中,找出和为target的组合。给出的列表中不存在重复数据,但是答案中可以重复使用。注意:给出的列表不是排序之后的List。

解题思路:

我们可以看出每个数最多的使用次数是int(target/candidates[i])。并且超过target的数据不会出现在答案中,所以我们可以先求出每个数在答案当中出现的最多个数,同时求出我们寻找可能组合的最大范围(减少时间开销)。

watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzI5NjAwMTM3_size_16_color_FFFFFF_t_70

eg 2 3 6就是我们需要遍历的范围

在遍历的过程中,维护好数字对应的数量List,DFS就可以。

  1. class Solution:
  2. def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
  3. candidates.sort()
  4. len_c = len(candidates)
  5. # print(len_c)
  6. num = [0] * len_c
  7. len_max = len_c
  8. for i in range(len_c):
  9. num[i] += int(target / candidates[i])
  10. if num[i] == 0 and i < len_max:
  11. len_max = i
  12. # print(len_max, num)
  13. ans = []
  14. tmp = []
  15. began = 0
  16. return DFS(ans, tmp, 0, target, len_max ,num, candidates,began)
  17. def DFS(ans, tmp, cor, target, len_max, num, candidates, began):
  18. if cor > target:
  19. return ans
  20. if cor == target:
  21. new_ans = []
  22. for i in range(len(tmp)):
  23. new_ans.append(tmp[i])
  24. ans.append(new_ans)
  25. return ans
  26. for i in range(began, len_max):
  27. if num[i] != 0 and cor + candidates[i] <= target:
  28. tmp.append(candidates[i])
  29. num[i] -= 1
  30. cor += candidates[i]
  31. ans = DFS(ans, tmp, cor, target, len_max, num, candidates, i)
  32. tmp.pop()
  33. num[i] += 1
  34. cor -= candidates[i]
  35. return ans

发表评论

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

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

相关阅读