Home Leetcode 39 - Combination Sum
Post
Cancel

Leetcode 39 - Combination Sum

Link to problem

Problem

Given an array of distinct integers candidates and a target integer target, return a list of all unique combinations of candidates where the chosen numbers sum to target. You may return the combinations in any order.

The same number may be chosen from candidates an unlimited number of times. Two combinations are unique if the frequency of at least one of the chosen numbers is different.

The test cases are generated such that the number of unique combinations that sum up to target is less than 150 combinations for the given input.

Note: all elements of candidates are distinct.

Solution

Basically, the algorithm tries out all different combinations to see if the combination matches the sum target. We try add numbers, and if in the end we could not match target, pop numbers and try a different number from candidates. This is essentially backtrack.

  1. Adding a number from candidates, the target becomes target - selected_candidate.
  2. Add another number and repeat the process.
  3. If target becomes 0, push the set of selected number to output. If target < 0 return as this combination failed.
  4. Pop a number from the selected set, try another number.

Since every elements of candidates are distinct, to prevent duplicated combination, we simply choose next number from candidates when backtracking (popping numbers from selected set).

Implementation

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
class Solution {
public:
    void runner(vector<int>& candidates, int target,
             vector<int>& temp, int start, vector<vector<int>>& output) {
        if (target == 0) {
            output.push_back(temp);
            return;
        }
        else if (target < 0) return;

        for (int i = start; i < candidates.size(); i++) {
            temp.push_back(candidates[i]);
            runner(candidates, target - candidates[i], temp, i, output);
            temp.pop_back();
        }
    }

    vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
        vector<vector<int>> output;
        vector<int> temp;

        runner(candidates, target, temp, 0, output);

        return output;
    }
};

Follow Up

(Probably will do these also)

  • 40 - Combination Sum II
  • 216 - Combination Sum II
This post is licensed under CC BY 4.0 by the author.