-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGenerate all binary strings without consecutive 1’s
81 lines (57 loc) · 1.67 KB
/
Generate all binary strings without consecutive 1’s
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
// Java program to Generate all binary string without
// consecutive 1's of size K
import java.util.*;
import java.lang.*;
public class BinaryS
{
public static String toString(char[] a) // Array conversion to String--
{
String string = new String(a);
return string;
}
static void generate(int k, char[] ch, int n)
{
// Base Condition when we
// reached at the end of Array**
if (n == k) {
// Printing the Generated String**
// Return to the previous case*
System.out.print(toString(ch)+" ");
return;
}
// If the first Character is
//Zero then adding**
if (ch[n - 1] == '0') {
ch[n] = '0';
generate(k, ch, n + 1);
ch[n] = '1';
generate(k, ch, n + 1);
}
// If the Character is One
// then add Zero to next**
if (ch[n - 1] == '1') {
ch[n] = '0';
// Calling Recursively for the
// next value of Array
generate(k, ch, n + 1);
}
}
static void fun(int k) {
if (k <= 0) {
return;
}
char[] ch = new char[k];
// Initializing first character to Zero
ch[0] = '0';
// Generating Strings starting with Zero--
generate(k, ch, 1);
// Initialized first Character to one--
ch[0] = '1';
generate(k, ch, 1);
}
public static void main(String args[]) {
int k = 3;
//Calling function fun with argument k
fun(k);
}
}