-
Notifications
You must be signed in to change notification settings - Fork 63
/
54_print_subset_of_size_k_of_array.cpp
64 lines (61 loc) · 1.3 KB
/
54_print_subset_of_size_k_of_array.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
//
// main.cpp
// subset
//
// Created by Prince Kumar on 09/09/19.
// Copyright © 2019 Prince Kumar. All rights reserved.
//
// Print all subset of size 'k' of array of size 'n'
#include <iostream>
#include<vector>
#include <math.h>
#include <algorithm>
using namespace std;
int main()
{
cout<<"Enter number of elemnets in array : "<<endl;
int n; cin>>n;
cout<<"Enter the size of subset : "<<endl;
int k ; cin>>k;
int a[n];
cout<<"Enter the numbers : "<<endl;
for(int i=0;i<n;i++)
{
cin>>a[i];
}
for(int i=1;i<pow(2,n);i++)
{
vector<int> v;
int x=i; // x=8
while(x>0)
{
int z = x%2; // 0 0 0 1
v.push_back(z);
x=x/2; // 4 2 1 0
}
int p = n- (int)v.size();
for(int j=1;j<=p;j++)
{
v.push_back(0);
}
reverse(v.begin(), v.end());
int count=0;
for(int i=0;i<v.size();i++)
{
if(v[i]==1)
count++;
}
if(count==k)
{
for(int i=0;i<v.size();i++)
{
if(v[i]==1)
{
cout<<a[i]<<" ";
}
}
cout<<endl;
}
v.clear();
}
}