Question:
eg: I/p: N = 5, K =3
O/p:
1 2 3
1 2 4
1 2 5
1 3 4
1 3 5
1 4 5
2 3 4
2 3 5
2 4 5
3 4 5
Answer:
#include <stdio.h>
#include <stdlib.h>
#include <vector>
#include <iostream>
using namespace std;
void subsetsnkHelp(int idx, int n, int k,vector<int> &subres,vector<vector<int>> &res){
//end case!!!
if(subres.size()==k){
res.push_back(subres);
return;
}
for(int i=idx;i<=(n-(k-subres.size()-1));++i){
subres.push_back(i);
subsetsnkHelp(i+1,n,k,subres,res);
subres.pop_back(); //Backtrack!!! Important! As only maintain one vector to use as stack.
}
return;
}
vector<vector<int>> subsetsnk (int n, int k){
vector<vector<int>> res;
vector<int> subres;
if(!n || !k) return res;
subsetsnkHelp(1,n,k,subres,res);
return res;
}
int main(){
vector<vector<int>> arr = subsetsnk(5,3);
for(int i=0; i<arr.size();++i){
for(int j=0;j<arr[0].size();++j){
cout<<arr[i][j]<<" ";
}
cout<<endl;
}
getchar();
return 0;
}
No comments:
Post a Comment