Title 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 is chosen from C unlimited number of times.
Note:
- All numbers (including target) would be positive integers.
- Elements in a combination (a1, a 2, ..., aK) must is in non-descending order. (ie, a1≤ a2≤ ... ≤ ak).
- The solution set must not contain duplicate combinations.
For example, given candidate set and 2,3,6,7 target 7 ,
A Solution set is:
[7]
[2, 2, 3]
Problem Solving Ideas:
First sort the array, then apply the backtracking and greedy algorithm, first start with the smallest number, as far as possible to put the number into the list, if the number of joined too many causes the following number can be mixed equal to target will be added before the number of pop, into the next number, so repeated.
The code is as follows:
public class Solution {public list<list<integer>> combinationsum (int[] candidates,int target) { Arrays.sort (candidates); list<list<integer>> result = new arraylist<list<integer>> (); GetResult (result, new ArrayList <Integer> (), candidates, target, 0); return result;} public void GetResult (list<list<integer>> result,list<integer> Current, int[] candiates, int target, int start) {if (Target > 0) {for (int i = start; I < candiates.length && target >= candiates[i]; i++) {CU Rrent.add (Candiates[i]); GetResult (result, current, candiates, target-candiates[i], i); Current.remove (Current.size ( )-1);}} else if (target = = 0) {result.add (new arraylist<integer> (current));}}}
Java [Leetcode 39]combination Sum