[Leetcode] [Java] Combinations

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

Test Instructions:

Given two integers n and K, return 1 ... all combinations of k digits in N.

Say

If N=4 and k=2, the solution is:

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

Algorithm Analysis:

Recursive processing of sub-problems with a loop.

AC Code:

public class Solution {public    arraylist<arraylist<integer>> combine (int n, int k)    {         ArrayList <ArrayList<Integer>> res = new arraylist<arraylist<integer>> ();        if (n<=0 | | n<k)          return res;         Helper (N,k,1,new arraylist<integer> (), res);        return res;    }    private void Helper (int n, int k, int start, arraylist<integer> item, arraylist<arraylist<integer>> Res    {         if (item.size () ==k)         {             res.add (new arraylist<integer> (item));            return;         }         for (int i=start;i<=n;i++)//try each possibility number in the current position         {             item.add (i);             Helper (n,k,i+1,item,res); After selecting number for current position, process next position              Item.remove (Item.size ()-1);//Clear the Curren T position to try next possible number          }}}     


Copyright NOTICE: This article is the original article of Bo Master, reprint annotated source

[Leetcode] [Java] Combinations

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.