简繁EN

LeetCodeNo. 115

[LeetCode with Python] 39. Combination Sum

Contents

Problem

Problem page: https://leetcode.com/problems/combination-sum/
Topics: Array, Backtracking
Difficulty: Medium
Similar problems: (M) Letter Combinations of a Phone Number, (M) Combination Sum II, (M) Combinations, (M) Combination Sum III, (M) Factor Combinations

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

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

Note:

  1. All numbers (including target) will be positive integers.
  2. Elements in a combination (a1, a2, … , ak) must be in non-descending order. (ie, a1 ≤ a2 ≤ … ≤ ak).
  3. The solution set must not contain duplicate combinations.

For example, given candidate set 2,3,6,7 and target 7,

A solution set is:
[7]
[2, 2, 3]


Analysis

A pretty classic combination problem that uses recursion and backtracking. Each element can be used more than once. The set passed in might not be in order, so I'd sort it first just to be safe (maybe that's not needed? There are no duplicate elements in a set, so there won't be any duplicate solutions). There are two things worth thinking about here:
Why can't I use dynamic programming to solve this problem? What kinds of problems can I use dynamic programming for, and what exactly is dynamic programming? I've always been puzzled by how to define dynamic programming. But there's at least one thing I'm sure of: dynamic programming is for optimization problems, not combination problems. For example, if the problem were changed so I had to pick a subset whose sum comes as close as possible to the given target without going over target, it would be a classic knapsack problem in dynamic programming. (That doesn't seem quite right. Interleaving String is a DP problem, and it's a permutation problem, not an optimization problem. Maybe a DP problem has to be one you can break down iteratively.)
The infinite recursion problem. Watch the used variable in the code, since values in the set can be used more than once...
Also, the problem says "a set of candidate numbers". Since it's a set, there are no duplicate elements in numbers.
(I feel like I still don't quite understand this problem)


Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
class Solution:

def __init__(self):
self.nums = None
self.len_nums = 0
self.total = 0
self.combinations = [ ]

def doCombinationSum(self, prefix, prefix_total, start, last, used):
if start >= self.len_nums:
return
num = self.nums[start]

result = True
# Only continue if this is the first time I've considered this element, or if I've considered it before and used it in the previous round.
if num != last or used: ###
if prefix_total + num == self.total:
new_prefix = prefix[:]
new_prefix.append(num)
self.combinations.append(new_prefix)
return
elif prefix_total + num < self.total:
new_prefix = prefix[:]
new_prefix.append(num)
self.doCombinationSum(new_prefix, prefix_total + num, start + 1, num, True)
self.doCombinationSum(new_prefix, prefix_total + num, start, num, True)
else:
return
# I can only skip this element and add 1 to the index the first time I consider it. Otherwise I'll add duplicate combinations.
if num != last: ###
self.doCombinationSum(prefix, prefix_total, start + 1, num, False)
return True

# @param candidates, a list of integers
# @param target, integer
# @return a list of lists of integers
def combinationSum(self, candidates, target):
self.combinations = [ ]
self.nums = candidates
self.nums.sort()
self.len_nums = len(self.nums)
if 0 == self.len_nums:
return [ ]
self.total = target
self.doCombinationSum([ ], 0, 0, -1, True)
return self.combinations

Article link: https://xnerv.wang/en/leetcode-combination-sum/