- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- 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 combinations of k-bit numbers with n bits set where 1 <= n <= k in sorted order in C++
Suppose we have a number k. Find all possible combinations of k- bit numbers with n set-bits where 1 <= n <= k. As result we will print all numbers with one set bit first, followed by numbers with two bits set, up to the number where all bits are set. If two numbers have same number of set bits, then the smaller number comes first. So if k = 3, then the numbers will be [001, 010, 100, 011, 101, 110, 111]
Here we will use dynamic programming approach to find all possible combinations of k-bit numbers with n set-bits where 1 <= n <= k. This problem can also be divided into two parts. We will find all combinations of length k where n number of 1s will by prefixing 0 to all combinations of length k – 1 with n ones and 1 to all combinations of length k – 1. with n – 1 ones.
Example
#include<iostream> #include<vector> #define K 16 using namespace std; vector<string> table[K][K]; void getCombinations(int k) { string str = ""; for (int bit = 0; bit <= k; bit++) { table[bit][0].push_back(str); str = str + "0"; } for (int bit = 1; bit <= k; bit++) { for (int n = 1; n <= bit; n++) { for (string str : table[bit - 1][n]) table[bit][n].push_back("0" + str); for (string str : table[bit - 1][n - 1]) table[bit][n].push_back("1" + str); } } for (int n = 1; n <= k; n++) { for (string str : table[k][n]) cout << str << " "; cout << endl; } } int main() { int k = 4; getCombinations(k); }
Output
0001 0010 0100 1000 0011 0101 0110 1001 1010 1100 0111 1011 1101 1110 1111