Combinations <leetcode>

Source: Internet
Author: User

Given two integersNAndK, Return all possible combinationsKNumbers out of 1...N.

For example,
IfN= 4 andK= 2, a solution is:

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

Algorithm: This question is very simple, but I didn't expect it at the time. I suddenly realized it was just a query on the Internet, that is, to construct a solution space, and then solve it with backtracing. soeasy, I don't want to talk about it anymore. Go to the Code:

 1 class Solution { 2 public: 3     vector<vector<int>>  result; 4     vector<int>  node; 5     vector<vector<int> > combine(int n, int k) { 6          result.clear(); 7          node.resize(k); 8          doit(0,n,k,1); 9          return result;10     }11     void doit(int dep,int n,int k,int start)12     {13         if(dep==k)14         {15             result.push_back(node);16             return;17         }18         else19         {20             for(int i=start;i<=n-k+1+dep;i++)21             {22                 node[dep]=i;23                 doit(dep+1,n,k,i+1);24             }25         }26     }27 };

 

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.