- Combination Sum Add to List QuestionEditorial Solution My Submissions
Total Accepted: 128797
Total Submissions: 364687
Difficulty: Medium
Contributors: Admin
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.
The solution set must not contain duplicate combinations.
For example, given candidate set [2, 3, 6, 7] and target 7,
A solution set is:
[
[7],
[2, 2, 3]
]
Subscribe to see which companies asked this question
思路描述
先用快速排序进行排序。
借助有序字典,从大值到小值进行广度优先遍历算法,记录符合remainder为0 的路径。
/**
* @param {number[]} candidates
* @param {number} target
* @return {number[][]}
*/
var g_result = [];
var g_target = [];
var g_candidates ;
var combinationSum = function(candidates, target) {
g_result = [];
g_target = target;
qSort(candidates,0,candidates.length-1);
g_candidates = candidates;
//genCombination(target, []);
genCombination1(target, [], g_candidates.length-1);//当数组变成有序之后,利用有序可以去掉重复的遍历路径
return g_result;
};
var qSort= function(array , low , high)
{
if (low < high)
{
var pivotIndex = partition(array , low ,high);
qSort(array, low , pivotIndex -1);
qSort(array, pivotIndex + 1 , high);
}
}
var partition = function(array , low , high)
{
var pivot = array[low];
if(low > high)
{
while(low<high && pivot < array[high] ){ high--;}
if(low < high) array[low++] = array[high];
while(low<hight && pivot > array[low] ){ low++;}
if(low < high )array[high++] = array[low];
}
array[low] = pivot;
return low;
}
var genCombination1 = function(remainder , combination , maxIndex )
{
if(remainder < 0)
{
return
}
else if (remainder > 0)
{
for(var i = maxIndex ; i>= 0 ; i--)//这是遍历的不一样的地方。
{
var newcomb = combination.concat();
newcomb.push(g_candidates[i]);
genCombination1( remainder - g_candidates[i] ,newcomb,i );
}
return
}
else
{
g_result.push(combination);
}
}
var genCombination = function(remainder , combination )
{
console.log("remainder:"+remainder+" combination"+combination);
if(remainder < 0)
{
return
}
else if (remainder > 0)
{
for(var i = 0 ; i < g_candidates.length ; i++)
{
var newcomb = combination.concat();
newcomb.push(g_candidates[i]);
genCombination( remainder - g_candidates[i] ,newcomb);
}
return
}
else
{
g_result.push(combination);
}
}