Generate all permutations of a given length such that every permutation has more or equals 1’s than 0’s in all prefixes of the permutation.
Examples:
Input: len = 4
Output: 1111 1110 1101 1100 1011 1010
Note that a permutation like 0101 can not be in output because
there are more 0's from index 0 to 2 in this permutation.
Input: len = 3
Output: 111 110 101
Input: len = 2
Output: 11 10
Like permutation generation problems, recursion is the simplest approach to solve this. We start with an empty string, attach 1 to it and recur. While recurring, if we find more 1’s at any point, we append a 0 and make one more recursive call.
Below is the implementation:
C++
#include <iostream>
#include <cstring>
using namespace std;
void generate( int ones, int zeroes, string str, int len)
{
if (len == str.length())
{
cout << str << " " ;
return ;
}
generate(ones+1, zeroes, str+ "1" , len);
if (ones > zeroes)
generate(ones, zeroes+1, str+ "0" , len);
}
int main()
{
string str = "" ;
generate(0, 0, str, 4);
return 0;
}
|
Java
class GFG {
static void generate( int ones, int zeroes, String str, int len) {
if (len == str.length()) {
System.out.print(str + " " );
return ;
}
generate(ones + 1 , zeroes, str + "1" , len);
if (ones > zeroes) {
generate(ones, zeroes + 1 , str + "0" , len);
}
}
public static void main(String[] args) {
String str = "" ;
generate( 0 , 0 , str, 4 );
}
}
|
Python3
def generate(ones, zeroes, str , len1):
if (len1 = = len ( str )):
print ( str ,end = " " )
return
generate(ones + 1 , zeroes, str + "1" , len1)
if (ones > zeroes):
generate(ones, zeroes + 1 , str + "0" , len1)
if __name__ = = '__main__' :
str = ""
generate( 0 , 0 , str , 4 )
|
C#
using System;
public class GFG {
static void generate( int ones, int zeroes, String str, int len) {
if (len == str.Length) {
Console.Write(str + " " );
return ;
}
generate(ones + 1, zeroes, str + "1" , len);
if (ones > zeroes) {
generate(ones, zeroes + 1, str + "0" , len);
}
}
public static void Main() {
String str = "" ;
generate(0, 0, str, 4);
}
}
|
Javascript
<script>
function generate(ones, zeroes, str, len) {
if (len === str.length) {
document.write(str + " " );
return ;
}
generate(ones + 1, zeroes, str + "1" , len);
if (ones > zeroes) {
generate(ones, zeroes + 1, str + "0" , len);
}
}
var str = "" ;
generate(0, 0, str, 4);
</script>
|
Output:
1111 1110 1101 1100 1011 1010
Time Complexity: O(2N), as we are using two recursive calls. Where N is the given length of the string.
Auxiliary Space: O(N)
This article was contributed by Sachin. Please write comments if you find anything incorrect, or if you want to share more information about the topic discussed above.