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: 
**Below is the solution using Recursion as an approach in java**

```
public class NumberOfBinaryPatternsSpecificOnes {

    static int[] bitArray = new int[]{0,1}; // kept binary bits in array

    public static void main(String args[])
    {   
        System.out.println("Below are the patterns\n");
        int n = 4;
        int k = 2;
        drawBinaryPattern(n,"",k,0);
    }
    private static void drawBinaryPattern(int n,String seed,int numberOfOnes,int currentCount)
    {
        if(n==0)
        {
            if(currentCount==numberOfOnes){
                System.out.println(seed);
            }
            return;
        }   
        for(int j=0;j<bitArray.length;j++)
        {
            String temp = seed+bitArray[j];
            int currentcountTemp = bitArray[j]==1?(currentCount+1):(currentCount);

            if(currentcountTemp>numberOfOnes)
            {
                return;
            }
            drawBinaryPattern(n-1,temp,numberOfOnes,currentcountTemp);
        }
    }
}

```
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.