Java for Leetcode 039 combination Sum

Source: Internet
Author: User

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 of all, the topic of the bug, the actual test in C elements will not be duplicated, and therefore reduced a lot of difficulty, the simplest implementation method, DFS algorithm, Java implementation is as follows:

static public list<list<integer>> combinationsum (int[] candidates,int target) {List<list<integer >> list = new arraylist<list<integer>> (); Arrays.sort (candidates);d FS (list, candidates, 0, target, 0); return list;} static list<integer> List2 = new arraylist<integer> (); static void Dfs (List<list<integer>> List , int[] array, int result,int target, int depth) {if (result = = target) {list.add (new arraylist<integer> (List2)); RET Urn;} else if (depth >= array.length | | result > Target) return;for (int i = 0; I <= target/array[depth]; i++) {for (i NT J = 0; J < I; J + +) List2.add (array[depth]);d FS (list, array, result + array[depth] * I, Target, depth+1); for (int j = 0; J < i; j + +) Lis T2.remove (List2.size ()-1);}}

Java for Leetcode 039 combination Sum

Related Article

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.