[*] Combination

Source: Internet
Author: User

title :

Given-integers n and K, return all possible combinations of K numbers out of 1 ... n.

For example,
If N = 4 and k = 2, a solution is:

[  [2,4],  [3,4], [  2,3],  [up],  [1,3],  [1,4],]

Exercises

This problem is solved by using DFS (reference work breakii) as a method of cyclic recursive processing of sub-problems. n is the number of cycles, and K is a different number for each attempt. Use of backtracking.

The code is as follows:

1  PublicArraylist<arraylist<integer>> Combine (intNintk) {2arraylist<arraylist<integer>> res =NewArraylist<arraylist<integer>>();3         if(N <= 0| | N <k)4             returnRes;5arraylist<integer> item =NewArraylist<integer>(); 6DFS (N,k,1,item, res);//because it need to begin from 17         returnRes;8     }9     Private voidDfsintNintKintStart, arraylist<integer> item, arraylist<arraylist<integer>>Res) {Ten         if(item.size () = =k) { OneRes.add (NewArraylist<integer> (item));//because item is arraylist<t> so it would not be disappear from the stack to stack A             return; -         } -          for(inti=start;i<=n;i++){ the Item.add (i); -DFS (n,k,i+1, item,res); -Item.remove (Item.size ()-1); -         } +}

reference:http://blog.csdn.net/linhuanmars/article/details/21260217

Http://www.cnblogs.com/springfor/p/3877168.html

[*] Combination

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.