给出1到n的n个数,返回k个数组合
输入n=4,k=2
输出[1,2],[1,3],[1,4],[2,3],[2,4],[3,4]
#include <iostream>
#include<algorithm>
#include<string>
#include<vector>
#include<math.h>
using namespace std;
vector<int> s;
vector< vector<int> > result;
void back(int n,int k,int id)
{if(s.size()==k)
{result.push_back(s);
return;
}
int i;
for(i=id;i<=n-(k-s.size())+1;i++)
{s.push_back(i);
back(n,k,i+1);
s.pop_back();
}}
void Print(vector< vector<int> > a)
{
vector<vector<int> >::iterator p1;
vector<int>::iterator p2;
for (p1 = a.begin(); p1 != a.end(); p1++)
{
for (p2 = p1->begin(); p2 != p1->end(); p2++)
{
cout << "[" << *p2 << "]";
}
cout <<",";
}
}
int main()
{
int n,k;
cin>>n>>k;
back(n,k,1);
Print(result);
// 请在此输入您的代码
return 0;
}
|