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], ]
题目的意思就是求组合数,注意这道题和求排列数求排列数很相似,所以也可以用回溯法(DFS)
区别就是求组合数的时候,一个数如果使用过了就不要再使用了,下标的起点需要调整下。
class Solution {
public:
vector<vector<int>> combine(int n, int k) {
vector<bool> visited(n+1,false);
vector<int> curr;
vector<vector<int>> vv;
int i =1;
combinations(n,k,i,vv,curr,visited);
return vv;
}
void combinations(int n, int k, int i, vector<vector<int>> &vv, vector<int> &curr, vector<bool> &visited){
if(curr.size()==k){
vv.push_back(curr);
return;
}
for(; i<=n; ++i){
if(visited[i]==false){
visited[i]=true;
curr.push_back(i);
combinations(n,k,i+1,vv,curr,visited);
curr.pop_back();
visited[i]=false;
}
}
}
};
12ms AC
再精炼一下会发现其实visited只是针对于求排列数来说的,
class Solution {
public:
vector<vector<int>> combine(int n, int k) {
vector<int> curr;
vector<vector<int>> vv;
int i =1;
combinations(n,k,i,vv,curr);
return vv;
}
void combinations(int n, int k, int i, vector<vector<int>> &vv, vector<int> &curr){
if(curr.size()==k){
vv.push_back(curr);
return;
}
for(; i<=n; ++i){
curr.push_back(i);
combinations(n,k,i+1,vv,curr);
curr.pop_back();
}
}
};
还是12ms Ac,并不是最快的
上面的解法有点通用性,实际上并不是需要频繁的push_back或pop_back
class Solution {
public:
vector<vector<int> > combine(int n, int k) {
v.resize(k);
dfs(1, n, k);
return r;
}
private:
vector<vector<int> > r;
vector<int> v;
void dfs(int i, int n, int k) {
while (i <= n) {
v[v.size() - k] = i++;
if (k > 1)
dfs(i, n, k - 1);
else
r.push_back(v);
}
}
};
8ms AC