组合问题1

给出1到n的n个数,返回k个数组合

输入n=4,k=2

输出[1,2],[1,3],[1,4],[2,3],[2,4],[3,4]

#include 
#include
#include 
#include
#include
using namespace std;
vector s;
vector< vector > 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 > a)
{
	vector >::iterator p1;
	vector::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;
}

你可能感兴趣的:(力扣,leetcode)