LeetCode – Combination Sum
題目描述:
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.
Elements in a combination (a1, a2, … , ak) must be in non-descending order. (ie, a1 ≤ a2 ≤ … ≤ ak).
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]
給定一個數組,和一個目標數,使用給定數組中的數字,求出所有和等於目標數的可能組合。 例如給定2,3,6,7 ,可能組合是[7]和[2,2,3]
這個題目有兩個條件:
1. 數字是可以重復的
2. 組合必須是升序排列
3. 不能有重復組合
4. 所有數字都是正數
思路:
對數組遍歷,縮小目標數: target-= candidate[i]。如果target < candadite[i] ,中斷循環
使用1個數組:arr記錄當前遍歷情況,如果target為0,存入結果。
在遍歷數組過程中,添加當前元素:arr.Add(self),進入遞歸
拿掉當前元素: arr.Remove(self)
實現代碼:
public IList> CombinationSum(int[] candidates, int target)
{
if(candidates == null || candidates.Length == 0){
return null;
}
var arr = candidates.OrderBy(x=>x).ToList();
IList> result = new List>();
Travel(arr ,new List(), 0, target, result);
return result;
}
private void Travel(IList candidates, IList arr, int index, int target, IList> result){
if(target == 0 ){
result.Add(new List(arr));
return ;
}
for(var i = index ;i < candidates.Count; i++){
if(target < candidates[i]){
return;
}
arr.Add(candidates[i]);
Travel(candidates, arr, i + 1 , target - candidates[i], result);
arr.Remove(candidates[i]);
}
}