# Find all combinations of k-bit numbers with n bits set where 1 <= n <= k in sorted order in C++

C++Server Side ProgrammingProgramming

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

Live Demo

#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].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
Advertisements