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

方法一:第一种递归思路,要从1...n中选出k个数作为一个组合,那我们可以依次从1开始扫描,每个元素有两种选择,被选择和不被选,即如果1被选择,那么下一个子问题就是从2...n中选择出k-1个数,若1没被选择,那么下一个子问题就是从2..n中选择k个数。
 1 class Solution {
 2 public:
 3     vector<vector<int> > combine(int n, int k) {
 4         if( n<1 || k<1 || n<k ) return vector< vector<int> >();
 5         vector<int> path;   //存储路径
 6         ans.clear();        //ans存放所有答案
 7         dfs(path, 1, n, k);
 8         return ans;
 9     }
10     
11     void dfs(vector<int>& path, int i, int n, int k) {
12         if( k == 0 ) {  //若k为0,说明找到了一个组合
13             ans.push_back(path);
14             return ;
15         }
16         if( i > n ) return ;    //已经没有元素可以选择了
17         dfs(path, i+1, n, k);   //当前元素不选的情况
18         path.push_back(i);
19         dfs(path, i+1, n, k-1); //当前元素选择的情况
20         path.pop_back();
21     }
22     
23 private:
24     vector< vector<int> > ans;
25 };

还有另一种写法,即

 1 class Solution {
 2 public:
 3     vector<vector<int> > combine(int n, int k) {
 4         if( n<1 || k<1 || n<k ) return vector< vector<int> >();
 5         vector<int> path;   //存储路径
 6         ans.clear();        //ans存放所有答案
 7         dfs(path, 1, n, k);
 8         return ans;
 9     }
10     
11     void dfs(vector<int>& path, int i, int n, int k) {
12         if( k == 0 ) {  //若k为0,说明找到了一个组合
13             ans.push_back(path);
14             return ;
15         }
16         for(; i<=n; ++i) {
17             path.push_back(i);
18             dfs(path, i+1, n, k-1);
19             path.pop_back();
20         }
21     }
22     
23 private:
24     vector< vector<int> > ans;
25 };

 

方法二:递归转为迭代,具体思路subset那篇博文有,大致算法是统计其所有的组合,碰倒个数为k的组合输出
 1 class Solution {
 2 public:
 3     vector<vector<int> > combine(int n, int k) {
 4         if( n<1 || k<1 || n<k ) return vector< vector<int> >();
 5         vector< vector<int> > ans;
 6         vector< vector<int> > cols;
 7         cols.push_back(vector<int>());
 8         for(int i=1; i<=n; ++i) {
 9             int len = cols.size();
10             for(int j=0; j<len; ++j) {
11                 vector<int> tmp = cols[j];
12                 tmp.push_back(i);
13                 cols.push_back(tmp);
14                 if( tmp.size() == k ) ans.push_back(tmp);
15             }
16         }
17         return ans;
18     }
19 };

 

 

posted on 2014-10-07 16:48  bug睡的略爽  阅读(155)  评论(0编辑  收藏  举报

导航