Problem
Given a set of candidate numbers (c) and a target number (T), find all unique combinations in C where the candidate number s sums to T.
The same repeated number is chosen from C unlimited number of times.
Note:
All numbers (including target) would be positive integers.
Elements in a combination (A1, A2, ..., AK) must is 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]*
Ideas
Because each element can be used more than once, for a combination ("2,2,3" for example)
1. Select 2 First, then Target has 5 left. The second time can also choose 2, 3, but can not choose 6, because 6 has exceeded target. iteration repeats the process. "2,2,3" can be selected.
2. Repeat this process again, choose 3 for the first time, then target is 4, and the rest will not be available.
Code
Public classSolution { PublicList<list<integer>>Combinationsum(int[] candidates,intTarget) {list<list<integer>> result =NewArraylist<list<integer>> ();if(Candidates = =NULL|| Target <0){returnResult } arrays.sort (candidates); Helper (candidates, target, result,NewArraylist<integer> (),0);returnResult }Private void Helper(int[] candidates,intTarget, list<list<integer>> result, list<integer> solution,intBegin) {if(target = =0) {Result.add (NewArraylist<integer> (solution));return; } for(inti = begin; I < candidates.length && target >= candidates[i]; i++) {Solution.add (candidates[i]); Helper (candidates, target-candidates[i], result, solution, I); Solution.remove (Solution.size ()-1); } }}
Remove method parsing for additional ArrayList
The ArrayList Remove method has two overloaded versions. respectively is
publicremove(int);publicbooleanremove(Object);
The first method is to delete the element at the specified position, and the second method is to delete the first occurrence of the element with the parameter equal. So the question is, if the list is defined as:
List<Integer>=new ArrayList<Integer>();
Do you want to delete the element at the specified position or delete the number equal to the parameter?
This depends on the law of overloading:
Parameter type widening (type compatibility) > auto-boxing > variable-length parameters
So, if the elements in Mlist are there [1,2,3,4,5] , we call the method:
mList.remove(1)The result becomes [1,3,4,5] .
mList.remove(new Integer(1))the elements in the mlist are then called [3,4,5] eventually.
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Leetcode-combination Sum