Title:
Given A collection of candidate numbers (C) and a target number (T), find all unique combinations in c where the candidate numbers sums to T.
Each number in C is used once in the combination.
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 set10,1,2,7,6,1,5and target8,
A Solution set is:
[1, 7]
[1, 2, 5]
[2, 6]
[1, 1, 6]
Test Instructions:
and the topic "
Combination Sum "The only difference is that (C) The elements in the final combination of each result can only appear once at a time.
Algorithm Analysis:
Similarly, the topic is a problem of solving cyclic sub-problems, using recursion for depth-first search. The basic idea is to first order, 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 ( excluding The currently added elements) 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:
public class Solution {static arraylist<arraylist<integer>> res;static arraylist<integer> Solu; Public arraylist<arraylist<integer>> combinationSum2 (int[] candidates, int target) { res= new Arraylist<arraylist<integer>> (); Solu = new arraylist<integer> (); if (candidates==null| | Candidates.length ==0) return res; Arrays.sort (candidates); Getcombination (candidates,target,0,0); return res; } private static void Getcombination (int[] candidates,int target, int sum, int level) {if (sum>target) return;if (sum== Target) {if (Res.size () ==0) Res.add (new arraylist<integer> (Solu)); else if (!res.contains (Solu)) Res.add (new Arraylist<integer> (Solu));} for (int i=level;i<candidates.length;i++) {sum+=candidates[i];solu.add (candidates[i]); Getcombination ( CANDIDATES,TARGET,SUM,I+1);//Unlike combination sum, the same element in the same combination cannot be selected repeatedly 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 II