title: Given an array of candidates and a target value, the combination of the number of the added result of target is obtained.
Example:
For example, given candidate set and [2, 3, 6, 7]
target 7
,
A Solution set is:
[[7],[2, 2, 3]]
As can be seen from the example, the same number can be used multiple times, and the result is unique;
Problem Solving Ideas:
I personally feel that the topic is not difficult, in fact, is a recursive process, when the recursive condition is reached, the result is added to the result set;
First of all, the topic did not say to the array has what characteristics, so I first sorted the array, so that at some point can not find the result, the back is bigger than the target, naturally there is no result. Don't say much nonsense, look directly at the code;
The code is as follows:
1 ImportJava.util.*;2 Public classSolution {3 PublicList<list<integer>> Combinationsum (int[] candidates,inttarget) {4List<list<integer>> llist =NewArraylist<list<integer>>(); The final result set 5 if(Candidates = =NULL|| Candidates.length < 1 | | Target < 1 )6 returnllist;7 Arrays.sort (candidates); sort so that you don't have to compute multiple times for the same result set 8list<integer> list =NewArraylist<integer>(); Temporary result save 9Combinationsumcore (candidates,list, target, 0, llist); core Functions Ten returnllist; One } A Public voidCombinationsumcore (int[] candidates,list<integer> List,intTargetintIndex, list<list<integer>>llist) - { - for(inti = index; i < candidates.length; i++) the { - if(Candidates[i] = =target) //equals, join result set - { -list<integer> result =NewArraylist<integer>(); + Result.addall (list); - Result.add (Candidates[i]); + Llist.add (result); A } at Elseif(Candidates[i] <target) //Less than, continue recursion - { -list<integer> result =NewArraylist<integer>(); - Result.addall (list); - Result.add (Candidates[i]); -Combinationsumcore (candidates, result, target-Candidates[i], I, llist); The I value is not changed here because the current value can be used more than once in } - else//is greater than, the subsequent number is greater than, so it is not possible to appear in the result set to { + Break; - } the } * } $}
Leetcode39--->combination Sum (finds and sets the target in the array)