Title:
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 (a 1 , a 2 , ..., a k ) must is in non-descending order. (Ie, a 1 ≤ < Span style= "" >a 2 ≤ ... ≤ a k ).
- The solution set must not contain duplicate combinations.
for example, given candidate Set 2,3,6,7 and target 7 ,
a solution set IS:&NBSP;
[7"
[2, 2, 3]
Test Instructions:
Given a set of integers(C) and a target value (T), From ( c " to find all the existing and unique combinations so that their sum equals ( t ).
< Span style= "Color:rgb (51,51,51); font-family: ' Helvetica Neue ', Helvetica,arial,sans-serif; line-height:30px "> The same repeating number can be in c unlimited selection. &NBSP;
< Span style= "Color:rgb (51,51,51); font-family: ' Helvetica Neue ', Helvetica,arial,sans-serif; line-height:30px "> Note:
1. All numbers including the target value are non-negative integers.
2. Elements in a group(a1, a2,. ..,ak) is arranged in ascending order.(ie,a1≤a2≤ ... ≤ak).
3. The combination of the final solution cannot appear duplicated.
For example, given a set of integral sets 2,3,6,7 and target value 7 ,&NBSP;
A solution set for:
[7" &NBSP;
[2, 2, 3] &NBSP;.
Algorithm Analysis:
This problem is a topic of solving cyclic sub-problems, using recursion for depth-first search. The basic idea is to first order, and then each recursive in the remaining element one by one to the result set, and the target minus the added element, and then the remaining elements (including the element currently added) to the next layer of recursion to solve the sub-problem. The complexity of the algorithm is a NP problem, so nature refers to the order of magnitude.
AC Code:
/** * The first impression of this problem should is Depth-first search (DFS). To solve DFS problem, recursion is a normal implementation. * Note that the candidates array was not sorted and we need to sort it first. */public class Solution {list<list<integer>> result; List<integer> solu;public list<list<integer>> combinationsum (int[] candidates, int target) {ResU lt = new arraylist<> (); Solu = new arraylist<> (); if (candidates = = NULL | | candidates.length = = 0) return result; Arrays.sort (candidates); Getcombination (candidates, target, 0, 0); return result; }public void Getcombination (int[] candidates, int target, int sum, int level) {if (sum>target) return;if (sum==target) { Result.add (New arraylist<> (Solu)); return;} for (int i=level;i<candidates.length;i++) {sum+=candidates[i];solu.add (candidates[i]); Getcombination ( Candidates, target, sum, i), Solu.remove (Solu.size ()-1); sum-=candidates[i];}}}
Copyright NOTICE: This article is the original article of Bo Master, reprint annotated source
[Leetcode] [Java] Combination Sum