Leetcode Combinations-----java

Source: Internet
Author: User

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],]

All results of C (k,n) are obtained.

It is simpler and more efficient to use backtracking (backtracking) to explain the problem.

 Public classSolution { PublicList<list<integer>> Combine (intNintk) {List<List<Integer>> res =NewArraylist<list<integer>>(); Con (N,k,0,0,res,New int[K]); returnRes; }     Public voidCon (intNintKintNumintstart,list<list<integer>> Res,int[] ans) {        if(num = =k) {ArrayList<Integer> TT =NewArraylist<integer>();  for(inti = 0;i<k;i++) Tt.add (Ans[i]);            Res.add (TT); return ; }         for(inti = start;i<n;i++) {Ans[num]= I+1; Con (N,k,num+1,i+1, Res,ans); }        return ;}}

One thing that can be fixed is that the for loop in con is changed to

for (int i = start;i<=n-(k-num); i++)

This can further increase the speed. Also, setting res as a global variable would look good in code.

Leetcode Combinations-----java

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.