
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find All Distinct Subsets of a Given Set in C++
Here we will see how to display all distinct subsets of a given set. So if the set is {1, 2, 3}, then the subsets will be {}, {1}, {2}, {3}, {1, 2}, {2, 3}, {1, 3}, {1, 2, 3}. The set of all subsets is called power set. The power set has 2n elements.
We will loop through 0 to 2n (excluding), in each iteration we will check whether the ith bit in the current counter is set, then print ith element.
Example
#include<iostream> #include<cmath> using namespace std; void showPowerSet(char *set, int set_length) { unsigned int size = pow(2, set_length); for(int counter = 0; counter < size; counter++) { cout << "{"; for(int j = 0; j < size; j++) { if(counter & (1<<j)) cout << set[j] << " "; } cout << "}" << endl; } } int main() { char set[] = {'a','b','c'}; showPowerSet(set, 3); }
Output
{} {a } {b } {a b } {c } {a c } {b c } {a b c }
Advertisements