-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathAllPossibleBlocks.java
More file actions
87 lines (69 loc) · 1.77 KB
/
AllPossibleBlocks.java
File metadata and controls
87 lines (69 loc) · 1.77 KB
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
82
83
84
85
86
87
/*
Given an integer n, print/output all possible if blocks for it. Say n=2 output should be
if {
}
if {
}
<newline>
if {
if {// here should exist two spaces before each inner block
}
}
*/
/*
a trick using stringbuilder in dfs:
int length = sb.length();
sb.append(...);
dfs(..., sb);
sb.setLength(length);
*/
import java.util.*;
public class AllPossibleBlocks {
// the key problem is how to deal with the indentation. Decouple the problem!!!!
// Time: O(2 ^ 2n) Space: O(n ^ 2) since n ^ 2 is the stringbuilder's space
public static void allBlocks(int n) {
char[] parentheses = new char[n * 2];
helper(parentheses, n, n, 0);
}
private static void helper(char[] parentheses, int leftRemain, int rightRemain, int index) {
// base case
if (leftRemain == 0 && rightRemain == 0) {
printBlock(parentheses);
return;
}
if (leftRemain > 0) {
parentheses[index] = '{';
helper(parentheses, leftRemain - 1, rightRemain, index + 1);
}
if (rightRemain > leftRemain) {
parentheses[index] = '}';
helper(parentheses, leftRemain, rightRemain - 1, index + 1);
}
}
// formating the output
private static void printBlock(char[] parentheses) {
int heading = 0;
System.out.println("***********");
for (int i = 0; i < parentheses.length; i++) {
if (parentheses[i] == '{') {
printSpace(heading);
System.out.println("if {");
heading += 2;
} else {
heading -= 2;
printSpace(heading);
System.out.println("}");
}
}
System.out.println("***********");
}
private static void printSpace(int heading) {
while (heading > 0) {
System.out.print(" ");
heading--;
}
}
public static void main(String[] args) {
allBlocks(3);
}
}