I am trying to write a logic where I want to generate a list of binary strings of given size n
and also the string should have maximum of k
bits set to 1
.
Example:
If n = 3, k = 1 ==> the number of 1's can be 0 or 1.
Then the output should be 000, 001, 010, 100
Below is the logic I have used with the help of this link as a reference:
Here n
is same as arr.length
.
static void generateAllBinaryStrings(int n, int arr[], int i, List<String> res, int k) {
if (i == n) {
StringBuilder sb = new StringBuilder();
int count = 0;
for (int j = 0; j < arr.length; j++) {
int val = arr[j];
if (val == 1) {
count++;
}
sb.append(val);
}
if (count <= k) {
res.add(sb.toString());
}
return;
}
arr[i] = 0;
generateAllBinaryStrings(n, arr, i + 1, res, k);
arr[i] = 1;
generateAllBinaryStrings(n, arr, i + 1, res, k);
}
public static void main(String args[]) {
int n = 3;
int[] arr = new int[n];
int k = 1;
int i = 0;
List<String> res = new ArrayList<>();
generateAllBinaryStrings(n, arr, i, res, k);
System.out.println(res);// Prints [000, 001, 010, 100]
}
This code is working fine, but this logic generates all possible binary string then filters based on the number of 1's in the string.
Is there any less time complex algorithm for this problem.