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], ]
Subscribe to see which companies asked this question
思路:
例:n = 4, k = 3;有combs,comb数组
组合情况有:
1)1 2 3
2)1 2 4
3)1 3 4
4)2 3 4
生成过程:
comb=[], k=3,初始状态;
comb=[1], k=2,加入1;
comb=[1,2], k=1,加入2;
comb=[1,2,3], k=0;加入3,结果添加到combs;
comb=[1,2], k=1;去掉3
comb=[1,2,4], k=0;加入3,结果添加到combs;
comb=[1,2], k=1,去掉4;
comb=[1], k=2,这时由于已经遍历到4(==n),要再去掉2;
comb=[1,3], k=1,加入3;
comb=[1,3,4], k=0,加入4,结果添加到combs;
comb=[1,3], k=1,去掉4;
comb=[1], k=2,这时由于已经遍历到n(==4),要再去掉3;
comb=[1,4], k=1,加入4;已经到n;
comb=[1], k=2,去掉4;
comb=[], k=3,去掉1;
comb=[2], k=2,加入2;
comb=[2,3], k=1,加入3;
comb=[2,3,4], k=0,加入4,结果添加到combs;
c++ code:
class Solution {
public:
vector<vector<int>> combine(int n, int k) {
vector<vector<int>> combs;
vector<int> comb;
combine(combs,comb,1,n,k);
return combs;
}
void combine(vector<vector<int>> &combs, vector<int> &comb,int begin,int n,int k) {
if(k==0){
combs.push_back(comb);
return;
}
for(int i=begin;i<=n;i++) {
comb.push_back(i);
combine(combs,comb,i+1,n,k-1);
comb.pop_back();
}
}
};