77组合
class Solution {
public:
vector<vector<int>>res;
vector<int>path;
vector<vector<int>> combine(int n, int k)
{
dg(n,k,1);
return res;
}
void dg(int n,int k,int start)
{
if(path.size()==k)
{
res.push_back(path);
return;
}
for(int i=start;i<=n-(k-path.size())+1;i++)
{
path.push_back(i);
dg(n,k,i+1);
path.pop_back();
}
}
};
class Solution {
public:
vector<int>path;
vector<vector<int>>res;
vector<vector<int>> combine(int n, int k)
{
vector<bool>state(n,false);
bt(n,k,state);
return res;
}
void bt(int n,int k,vector<bool>&state)
{
if(path.size()==k)
{
res.push_back(path);
return;
}
for(int i=1;i<=n;i++)
{
if(!state[i])
{
state[i]=true;
path.push_back(i);
bt(n,k,state);
path.pop_back();
state[i]=false;
}
}
}
};
有序和无序两个版本,无序需要加一个state数组,有序的剪枝具有局限性。