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:
- All numbers (including target) will be positive integers.
- Elements in a combination (a1, a2, … , ak) must be in non-descending order. (ie, a1 ≤ a2 ≤ … ≤ ak).
- The solution set must not contain duplicate combinations.
For example, given candidate set
2,3,6,7and target7,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 | class Solution: |
Article link: https://xnerv.wang/en/leetcode-combination-sum/
