Combinations [LeetCode]

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

  Summary: recursive functions

 1 class Solution {
 2 public:
 3     vector<vector<int> > combine(int n, int k) {
 4         vector<vector<int> > combinations;
 5         if(n == 0 || k == 0 || n < k)
 6             return combinations;
 7         if(k == 1){
 8             for(int i = 1; i <= n; i ++) {
 9                 vector<int> com(1, i);
10                 combinations.push_back(com);
11             }
12             return combinations;
13         }
14         
15         if(k == n){
16             vector<int> com;
17             for(int i = 1; i <= n; i ++) {
18                 com.push_back(i);
19             }
20             combinations.push_back(com);
21             return combinations;
22         }
23         
24         if(k <= n / 2){
25             for(int i = 0; i <= n - k; i ++){
26                 if(i == n - k){
27                     vector<int> com;
28                     for(int j = n - k + 1; j <= n; j ++)
29                         com.push_back(j);
30                     combinations.push_back(com);
31                     break;
32                 }
33                 
34                 int pick_num = i + 1;
35                 vector<vector<int> > sub_com = combine(n - pick_num, k - 1);
36                 for(auto item : sub_com) {
37                     for(int j = 0; j < item.size(); j ++){
38                         item[j] += pick_num;                    
39                     }
40                     item.insert(item.begin(), pick_num);
41                     combinations.push_back(item);
42                 }
43             }
44             return combinations; 
45         }else{
46             combinations = combine(n, n - k);
47             vector<vector<int> > counter_combinations;
48             for(auto item : combinations){
49                 vector<int> com; 
50                 int j = 0;
51                 for(int i = 1; i <= n ; i ++){   
52                     if(j < item.size() && item[j] == i)
53                         j ++;
54                     else 
55                         com.push_back(i);
56                 }
57                 counter_combinations.push_back(com);
58             }
59             return counter_combinations;
60         }
61             
62     }
63 };

 

posted @ 2013-11-05 15:14  假日笛声  阅读(524)  评论(0编辑  收藏  举报