Java [Leetcode 39]combination Sum

Source: Internet
Author: User

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

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.