39. Combination Sum [leetcode][javascript解法]
阿新 • • 發佈:2018-12-21
- 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);
}
}