LeetCode-Combination Sum
Description:
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]
Given an array and a target number, use the numbers in the given array to find a possible combination of all and equal to the target number. For example, given 2, 3, 6, 7, the combination may be [7] and [2, 2, 3].
There are two conditions for this question:
1. numbers can be repeated.
2. The combination must be in ascending order.
3. Duplicate combinations are not allowed.
4. All numbers are positive.
Ideas:
Traverse the array to reduce the number of targets: target-= candidate [I]. If target <candadite [I], the cycle is interrupted.
Use an array: arr records the current traversal. If the target is 0, the result is saved.
In the process of traversing the array, Add the current element: arr. Add (self) to go to recursion.
Remove the current element: arr. Remove (self)
Implementation Code:
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]);}}