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], ]
思路:和前面的那个组合的题目很相似,使用背包算法。这里实现了两种,还有一种是数组的,还需要避免重复的哪种。
#include <iostream>
#include <vector>
using namespace std;
/*
组合问题
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:
*/
/*从begin开始到end结束 选择k个数组成的组合*/
void helper(int begin,int end,int& k,vector<int>& com)
{
if(begin >end || k <0)
return;
com.push_back(begin);
k = k-1;
if(k == 0)
{
int i;
for(i=0;i<com.size();i++)
cout<<com[i]<<" ";
cout<<endl;
}
helper(begin+1,end,k,com);
com.pop_back();
k++;
helper(begin+1,end,k,com);
}
void Combination(int n,int k)
{
if(k <=0)
return ;
vector<int> com;
helper(1,n,k,com);
}
/*
从一个数组中找到指定数目的组合
*/
void helper_array(vector<int>& vec,int begin,int& k,vector<int>& com)
{
if(begin >= vec.size() || k <0)
return ;
com.push_back(vec[begin]);
k--;
if(k == 0)
{
int i;
for(i=0;i<com.size();i++)
cout<<com[i]<<" ";
cout<<endl;
}
helper_array(vec,begin+1,k,com);
com.pop_back();
k++;
int i;
for(i=begin+1;i<vec.size();)
{
if(vec[i] == vec[begin])
i++;
else
break;
}
helper_array(vec,i,k,com);
}
void Combination_array(vector<int>& vec,int k)
{
vector<int> com;
if(vec.size()==0 || k<=0)
return;
sort(vec.begin(),vec.end())
; helper_array(vec,0,k,com);
}
int main()
{
//Combination(4,2);
vector<int> vec(4);
for(int i=0;i<vec.size();i++)
vec[i] =i+1;
vec[3] = 1;
Combination_array(vec,2);
return 0;
}