Leetcode 216 combination Sum I II III

Source: Internet
Author: User

Combination Sum

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]

Idea: A thought that requires backtracking. Each number inside the array is superimposed recursively, each recursion is compared with sum and target, and if equal the result list,sum>target is discarded and returns false, if sum<target, the recursion continues. In the case of the first sum=target, after adding the result list, remove the element that is currently added to the current result, and continue to recursively return the following elements; In the case of the second Sum>target, You need to remove the last two elements of the current result and continue to recursively return the elements that follow. The third case is sum<target, eliminating the need to remove direct recursion.

Note that elements can be duplicated, so the next recursion begins with the current recursive element.

 Public classS039 {//backtracking--Backtracking Algorithm     PublicList<list<integer>> Combinationsum (int[] candidates,inttarget) {List<List<Integer>> result =NewArraylist<list<integer>>(); List<Integer> temp =NewArraylist<integer>(); Arrays.sort (candidates);//It's a critical step.Findconbination (result,temp,0,0, target,candidates); returnresult; }     Public BooleanFindconbination (list<list<integer>> result,list<integer> temp,intSumintLevelintTargetint[] candidates) {        if(Sum = =target) {Result.add (NewArraylist<> (temp));//Copy from memory to prevent subsequent changes from affecting it            return true; }Else if(sum>target) {            return false; }Else{             for(inti = level;i<candidates.length;i++) {//think about the role of the level parameterTemp.add (Candidates[i]);//sum + = candidates[i]; Consider the reason that this line commented out and added the sum to the next line of arguments                if(!findconbination (Result,temp,sum+candidates[i],i,target,candidates)) {//i indicates that the next recursion starts at the current recursive positioni =candidates.length; } temp.remove (Temp.size ()-1); }            return true; }    }}

Combination Sum II

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 (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 10,1,2,7,6,1,5 target 8 ,
A Solution set is:
[1, 7]
[1, 2, 5]
[2, 6]
[1, 1, 6]

Idea: The difference from the previous question is that the result requires that the elements in the same position appear only once, but that elements with the same value in the array can appear at the same time. The difference from the previous question is that the next recursion begins with the next element of the current recursion. In addition, the test set is not the same, the test set in the previous question does not appear to have the same element in the same array, so there is no extra weight. The same array will appear with the same element, so you have to skip the same elements as the elements move forward.

 Public classS040 { PublicList<list<integer>> combinationSum2 (int[] candidates,inttarget)        {Arrays.sort (candidates); List<List<Integer>> RETs =NewArraylist<list<integer>>(); List<Integer> ret =NewArraylist<integer>(); Find (candidates,0,0, Target,rets,ret); returnRETs; }     Public Static BooleanFindint[] candidates,intSumintLevelintTarget,list<list<integer>> rets,list<integer>ret) {        if(Sum = =target) {Rets.add (NewArraylist<>(ret)); return true; }Else if(Sum >target) {            return false; }Else{             for(inti = level;i<candidates.length;i++) {Ret.add (candidates[i]); if(!find (candidates,sum+candidates[i],i+1, Target,rets,ret)) {//i+1 indicates that the next recursion begins with the next element of the current recursion I=candidates.length; }                //Go heavy                 while(I<candidates.length-1&&ret.get (Ret.size ()-1) = = Candidates[i+1]) {i++; } ret.remove (Ret.size ()-1); }            return true; }    }}

Combination Sum III

Find all possible combinations of K numbers This add up to a number n, given this only numbers from 1 to 9 can is used and each combination should is a unique set of numbers.

Ensure that numbers within the set is sorted in ascending order.


Example 1:

Input: k = 3, n = 7

Output:

[[1,2,4]]


Example 2:

Input: k = 3, n = 9

Output:

[[1,2,6], [1,3,5], [2,3,4]


Idea: This question or refer to the first two questions, equivalent to the first two questions in the candidates array into nums={1,2,3,4,5,6,7,8,9}, and then in each comparison results with the result list size comparison, the current list size does not exceed K.
And it doesn't have to be extra heavy.
 Public classS216 { PublicList<list<integer>> combinationSum3 (intKintN) {List<List<Integer>> result =NewArraylist<list<integer>>(); List<Integer> temp =NewArraylist<integer>(); if(n<k* (k+1)/2| | n>45| | k>9| | K<1){            returnresult; }        int[] Nums = {1,2,3,4,5,6,7,8,9}; Find (Nums,k,n,0,0, result,temp); returnresult; }     Public Static BooleanFindint[] Nums,intKintNintSumintLevel , List<List<Integer>> result,list<integer>temp) {        if(Temp.size () >k| | Sum>N) {            return false; }Else if(Sum = = n&&temp.size () = =k) {Result.add (NewArraylist<>(temp)); return true; }Else{             for(inti = level;i<nums.length;i++) {Temp.add (nums[i]); if(!find (nums,k,n,sum+nums[i],i+1, Result,temp)) {i=nums.length; } temp.remove (Temp.size ()-1); }            return true; }    }}



Leetcode 216 combination Sum I II III

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.