Skip to content

Commit

Permalink
combination Sum DFS Solution
Browse files Browse the repository at this point in the history
  • Loading branch information
ignacio-chiazzo committed Feb 22, 2017
1 parent 3121d3d commit a05d4ec
Showing 1 changed file with 35 additions and 11 deletions.
46 changes: 35 additions & 11 deletions 39 Combination Sum.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@
// Note:
// All numbers (including target) will be positive integers.
// The solution set must not contain duplicate combinations.
// For example, given candidate set [2, 3, 6, 7] and target 7,
// A solution set is:
// For example, given candidate set [2, 3, 6, 7] and target 7,
// A solution set is:
// [
// [7],
// [2, 2, 3]
Expand All @@ -24,37 +24,61 @@
*/
var combinationSum = function(candidates, target) {
var result = [];

if(candidates === null || candidates.length === 0){
return result;
}

candidates.sort(function(a,b){return a > b ? 1 : -1});

var output = [];

generate(candidates, result, output, target, 0);

return result;
};

var generate = function(candidates, result, output, sum, index){
if(sum === 0){
result.push(output.slice());
result.push(output.slice());
}
if(sum < 0){
return;
}

for(var i = index; i < candidates.length; i++){
if(i > index && candidates[i] === candidates[i - 1]){
continue;
}

if(candidates[i] <= sum){
output.push(candidates[i]);
generate(candidates, result, output, sum - candidates[i], i);
output.pop();
}
}
}
}


// Another solution
var combinationSum = function(candidates, target) {
var results = [];
comb(candidates.sort(), 0, [], 0, target, results);
return results;
};

var comb = function(cand, index, partial, partialSum, target, results) {
if(target === partialSum) {
results.push(partial);
return;
}
if(cand.length === index || partialSum > target) {
return;
}

comb(cand, index + 1, partial, partialSum, target, results);
comb(cand, index, partial.concat([cand[index]].concat([cand[index]])),
partialSum + 2* cand[index], target, results);
comb(cand, index + 1, partial.concat([cand[index]]),
partialSum + cand[index], target, results);
};

0 comments on commit a05d4ec

Please sign in to comment.