Question: So i'm trying to generate all binaries of a size n but with the condition that only k 1s. i.e

for size n = 4, k=2, (there is 2 over 4 combinations)

```
1100
1010
1001
0110
0101
0011

```

I'm stuck and can't figure out how to generate this.

Answer: 
One approach is to generate all combinations of `k` values from the set of `n` numbers 0..`n-1`, and use these values to set the corresponding bits in the output.

[This Q&A](https://stackoverflow.com/q/127704/335858) explains how to generate all combinations of `k` elements from `n`. With these combinations in hand, use bitwise OR of `1 << v[c][i]` to produce the final result, where `v[c][i]` represents `i`-th number from combination number `c`.
int n = 4, k=2;

```
    for (int i = 0; i < Math.pow(2,n) ; i++) {
        int a = Integer.bitCount(i);
        if (a == k) System.out.println(Integer.toBinaryString(i));
    }

```

I think this is the simplest answer.