[Leedcode 216] Combination Sum III

Source: Internet
Author: User

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]
 Public classSolution {List<List<Integer>>Res; List<Integer>seq;  PublicList<list<integer>> combinationSum3 (intKintN) {//dfs,for loops and recursive overlays. //The level value needs to be saved because the result requirement is incremented, and in order to ensure that it is the number of K, each recursion, K minus oneres=NewArraylist<list<integer>>(); Seq=NewArraylist<integer>(); DFS (K,n,1,0); returnRes; }     Public voidDfsintKintNintStartintsum) {        if(sum==n&&k==0) {Res.add (NewArraylist<integer>(seq)); }Else if(sum>n| | k<=0)return;  for(inti=start;i<=9;i++) {seq.add (i); DFS (k-1,n,i+1,sum+i); Seq.remove (Seq.size ()-1); }    }}

[Leedcode 216] combination Sum 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.