Combinations--Leetcode

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


Basic ideas:

1, using recursion

2, each layer recursion, the use of the loop, the starting value of the loop, increment by layer. such as the first layer, starting from 1, the 2nd floor starts from the 2nd.

3. When a combination is generated. And with this group of cooperation samples, copy one, on this basis, generate the next combination.


Class Solution {public:    vector<vector<int> > Combine (int n, int k) {        vector<vector<int> > ans (1);        Helper (ans, 1, n, k);        Ans.pop_back ();        return ans;    }        void Helper (Vector<vector<int> > &ans, int start, int n, int k) {        if (!k)            return ans.push_back (ans . back ());                    for (int i=start; i<=n; i++) {            ans.back (). push_back (i);            Helper (ans, i+1, N, k-1);            Ans.back (). Pop_back ();}}    ;


Combinations--Leetcode

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.