Coder's Cat

LeetCode: Combination Sum

2020-02-03

Challenge Description

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:

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

Approach with Depth-First-Search (DFS)

This could be solved with depth-first search algorithms.

But we need to do a optimization for reduce the search space. After sorting the vector, when we enumerate each element in vector, if (cur_value > target) is true, we could just break out the loop.

class Solution {
vector<vector<int> > ans;

public:
void dfs(vector<int>& candidates, vector<int> path, int start, int target) {
if(target == 0){
ans.push_back(path);
return;
}
for(int k=start; k<candidates.size(); k++) {
int cur = candidates[k];
if(cur > target) break;

int remain = target - cur;
path.push_back(cur);
dfs(candidates, path, k, remain);
path.pop_back();
}
}

vector<vector<int> > combinationSum(vector<int>& candidates, int target) {
sort(candidates.begin(), candidates.end());
vector<int> path;
dfs(candidates, path, 0, target);
return ans;
}
};

Preparing for an interview? Check out this!

Join my Email List for more insights, It's Free!😋