问题描述
给定两个整数n和k,返回1,2,3…n的所有可能的k个整数的组合。
输入输出
输入:n=4,k=2;
输出:
[
[1,2],
[1,3],
[1,4],
[2,3],
[2,4],
[3,4],
]
C++实现
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
void getCombination(int n,int k,vector<int> &solution,vector<vector<int> > &result)
{
if(k==0)
{
vector<int> v=solution;
sort(v.begin(),v.end());
result.push_back(v);
return ;
}
for(int i=n;i>0;i--)
{
solution.push_back(i);
getCombination(i-1,k-1,solution,result);
solution.pop_back();
}
}
std::vector<std::vector<int> > combine(int n,int k)
{
vector <vector<int > > result;
vector<int> solution;
getCombination(n,k,solution,result);
return result;
}
void printResult(vector<vector<int> > &result)
{
for(int i=0;i<result.size();i++)
{
cout<<"{";
for(int j=0;j<result[i].size();j++)
{
cout<<" "<<result[i][j];
}
cout<<"}"<<endl;
}
}
int main()
{
int n=6;
int k=4;
vector<vector<int>> matrix=combine(n,k);
printResult(matrix);
return 0;
}