Combinations

Given two 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],
  [1,2],
  [1,3],
  [1,4],
]
C++:
01 void combineHelper(vector<vector<int>>& result, vector<int>& current,
02                    int k, int p, int n)
03 {
04     if(current.size()==k)
05     {
06         result.push_back(current);
07         return;
08     }
09     current.push_back(p);
10     combineHelper(result,current,k,p+1,n);
11     current.pop_back();
12     int remain=kcurrent.size();
13     if(np>=remain)
14     {
15         combineHelper(result,current,k,p+1,n);
16     }
17 }
18 
19 class Solution {
20 public:
21     vector<vector<int> > combine(int n, int k) {
22         // Start typing your C/C++ solution below
23         // DO NOT write int main() function
24         vector<vector<int>> result;
25         vector<int> current;
26         combineHelper(result,current,k,1,n);
27         return result;
28     }
29 };
Advertisements
This entry was posted in Array and linked list, Recursive. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s