Coder's Cat

LeetCode: Combination Sum


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:

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;

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

int remain = target - cur;
dfs(candidates, path, k, remain);

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!😋