-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path0022_generate_parentheses.html
More file actions
418 lines (353 loc) · 15.3 KB
/
Copy path0022_generate_parentheses.html
File metadata and controls
418 lines (353 loc) · 15.3 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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>LC 22: Generate Parentheses - Algorithm Visualization</title>
<link rel="stylesheet" href="styles.css">
<script src="https://d3js.org/d3.v7.min.js"></script>
</head>
<body>
<div class="container">
<div class="problem-info">
<h1><span class="problem-number">#22</span> Generate Parentheses</h1>
<p>Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.</p>
<div class="problem-meta">
<span class="meta-tag">🔄 Backtracking</span>
<span class="meta-tag">🔤 String</span>
<span class="meta-tag">⏱️ O(4^n / √n)</span>
<span class="meta-tag">💾 O(n)</span>
</div>
<div class="file-ref">
📄 Python: <code>python/0022_generate_parentheses/0022_generate_parentheses.py</code>
</div>
</div>
<div class="explanation-panel">
<h4>🧠 How It Works (Layman's Terms)</h4>
<p>Backtracking builds strings by making choices at each step:</p>
<ul>
<li><strong>Two rules:</strong> (1) Can add '(' if we have pairs left, (2) Can add ')' only if there's an unmatched '('</li>
<li><strong>Tree exploration:</strong> Each node makes choices, invalid paths are pruned automatically</li>
<li><strong>Base case:</strong> When string length = 2n, we have a valid combination</li>
<li><strong>Key insight:</strong> close_count < open_count ensures we never have more ')' than '('</li>
</ul>
</div>
<div class="visualization-section">
<h3>🎬 Step-by-Step Visualization</h3>
<div class="controls">
<label>n = </label>
<select id="nValue" style="padding: 8px; border-radius: 5px; border: 2px solid #ddd;">
<option value="1">1</option>
<option value="2">2</option>
<option value="3" selected>3</option>
</select>
<button class="btn btn-primary" onclick="step()">Step</button>
<button class="btn btn-success" onclick="autoRun()">Auto Run</button>
<button class="btn" style="background: #607d8b; color: white;" onclick="reset()">Reset</button>
</div>
<div class="status-message" id="statusMessage">
Click Step to explore the backtracking tree
</div>
<div style="display: flex; gap: 30px; flex-wrap: wrap; margin-top: 20px;">
<div style="flex: 2; min-width: 400px;">
<h4 style="margin-bottom: 10px;">🌳 Decision Tree</h4>
<svg id="treeViz" width="100%" height="400"></svg>
</div>
<div style="flex: 1; min-width: 200px;">
<h4 style="margin-bottom: 10px;">✅ Valid Combinations</h4>
<div id="resultsContainer" style="padding: 15px; background: #f5f5f5; border-radius: 12px; min-height: 200px;">
<span style="color: #999;">None yet...</span>
</div>
<h4 style="margin-top: 20px; margin-bottom: 10px;">📊 Current State</h4>
<div id="stateContainer" style="padding: 15px; background: #e3f2fd; border-radius: 12px;">
<div>Current: <strong id="currentStr">""</strong></div>
<div>Open: <strong id="openCount">0</strong></div>
<div>Close: <strong id="closeCount">0</strong></div>
</div>
</div>
</div>
</div>
<div class="code-section">
<h3>💻 Python Solution</h3>
<div class="code-block">
<pre>from typing import List
"""
LeetCode Generate Parentheses
Problem from LeetCode: https://leetcode.com/problems/generate-parentheses/
Description:
Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
Example 1:
Input: n = 3
Output: ["((()))","(()())","(())()","()(())","()()()"]
Example 2:
Input: n = 1
Output: ["()"]
Constraints:
1 <= n <= 8
"""
class Solution:
def generate_parenthesis(self, n: int) ->List[str]:
"""
Generate all combinations of well-formed parentheses.
Args:
n: Number of pairs of parentheses
Returns:
List[str]: All combinations of well-formed parentheses
"""
results = []
self._backtrack(results, '', 0, 0, n)
return results
def _backtrack(self, results: List[str], current: str, open_count: int,
close_count: int, max_pairs: int) ->None:
"""
Backtracking helper function to generate valid parentheses combinations.
Args:
results: List to collect all valid combinations
current: Current string being built
open_count: Number of opening parentheses used so far
close_count: Number of closing parentheses used so far
max_pairs: Maximum number of parentheses pairs
"""
if len(current) == max_pairs * 2:
results.append(current)
return
if open_count < max_pairs:
self._backtrack(results, current + '(', open_count + 1,
close_count, max_pairs)
if close_count < open_count:
self._backtrack(results, current + ')', open_count, close_count +
1, max_pairs)
def generate_parenthesis_iterative(self, n: int) -> List[str]:
"""
Generate all combinations of well-formed parentheses using an iterative approach.
Args:
n: Number of pairs of parentheses
Returns:
List[str]: All combinations of well-formed parentheses
"""
if n == 0:
return []
result = []
queue = [('', 0, 0)] # (current string, open count, close count)
while queue:
curr, open_count, close_count = queue.pop(0)
if len(curr) == 2 * n:
result.append(curr)
continue
if open_count < n:
queue.append((curr + '(', open_count + 1, close_count))
if close_count < open_count:
queue.append((curr + ')', open_count, close_count + 1))
return result
if __name__ == '__main__':
# Example usage based on LeetCode sample
solution = Solution()
# Example 1
n1 = 3
result1 = solution.generate_parenthesis(n1)
print(f"Example 1 (n={n1}): {result1}")
# Expected output: ["((()))","(()())","(())()","()(())","()()()"]
# Example 2
n2 = 1
result2 = solution.generate_parenthesis(n2)
print(f"Example 2 (n={n2}): {result2}")
# Expected output: ["()"]
# Additional example
n3 = 2
result3 = solution.generate_parenthesis(n3)
print(f"Example 3 (n={n3}): {result3}")
# Expected output: ["(())","()()"]
# Compare with iterative implementation
print("\nUsing iterative approach:")
result_iter = solution.generate_parenthesis_iterative(n1)
print(f"n={n1}: {result_iter}")
# Should match the output of the recursive approach
</pre>
</div>
</div>
</div>
<script>
let n = 3;
let treeData = null;
let nodeQueue = [];
let results = [];
let currentNode = null;
let isRunning = false;
let processedNodes = new Set();
class TreeNode {
constructor(str, open, close, parent = null, action = '') {
this.str = str;
this.open = open;
this.close = close;
this.parent = parent;
this.action = action;
this.children = [];
this.id = `${str}_${open}_${close}`;
this.visited = false;
this.isValid = str.length === n * 2;
}
}
function buildFullTree() {
const root = new TreeNode('', 0, 0, null, 'start');
buildTreeRecursive(root);
return root;
}
function buildTreeRecursive(node) {
if (node.str.length === n * 2) return;
if (node.open < n) {
const leftChild = new TreeNode(
node.str + '(',
node.open + 1,
node.close,
node,
'add ('
);
node.children.push(leftChild);
buildTreeRecursive(leftChild);
}
if (node.close < node.open) {
const rightChild = new TreeNode(
node.str + ')',
node.open,
node.close + 1,
node,
'add )'
);
node.children.push(rightChild);
buildTreeRecursive(rightChild);
}
}
function drawTree() {
const svg = d3.select("#treeViz");
svg.selectAll("*").remove();
const container = svg.node().parentElement;
const width = container.clientWidth;
const height = 400;
svg.attr("viewBox", `0 0 ${width} ${height}`);
const g = svg.append("g").attr("transform", "translate(40, 30)");
const treeLayout = d3.tree().size([width - 80, height - 80]);
const hierarchy = d3.hierarchy(treeData);
const treeNodes = treeLayout(hierarchy);
// Draw links
g.selectAll(".link")
.data(treeNodes.links())
.enter()
.append("path")
.attr("class", "link")
.attr("d", d3.linkVertical()
.x(d => d.x)
.y(d => d.y))
.attr("fill", "none")
.attr("stroke", d => {
if (!d.target.data.visited) return "#e0e0e0";
return d.target.data.action === 'add (' ? "#667eea" : "#4caf50";
})
.attr("stroke-width", d => d.target.data.visited ? 3 : 1);
// Draw nodes
const nodes = g.selectAll(".node")
.data(treeNodes.descendants())
.enter()
.append("g")
.attr("class", "node")
.attr("transform", d => `translate(${d.x}, ${d.y})`);
nodes.append("circle")
.attr("r", d => d.data.isValid ? 18 : 15)
.attr("fill", d => {
if (d.data === currentNode) return "#ff9800";
if (d.data.isValid && d.data.visited) return "#4caf50";
if (d.data.visited) return "#667eea";
return "#e0e0e0";
})
.attr("stroke", d => d.data === currentNode ? "#f57c00" : "none")
.attr("stroke-width", 3);
nodes.append("text")
.attr("dy", 4)
.attr("text-anchor", "middle")
.attr("font-size", d => d.data.isValid ? "10px" : "9px")
.attr("fill", d => d.data.visited || d.data === currentNode ? "white" : "#666")
.text(d => d.data.str || "ε");
}
function initQueue() {
nodeQueue = [treeData];
}
function step() {
if (nodeQueue.length === 0) {
document.getElementById('statusMessage').textContent =
`Done! Found ${results.length} valid combinations`;
return;
}
currentNode = nodeQueue.shift();
currentNode.visited = true;
document.getElementById('currentStr').textContent = `"${currentNode.str}"`;
document.getElementById('openCount').textContent = currentNode.open;
document.getElementById('closeCount').textContent = currentNode.close;
if (currentNode.isValid) {
results.push(currentNode.str);
document.getElementById('statusMessage').textContent =
`Found valid combination: "${currentNode.str}"!`;
renderResults();
} else {
let msg = `Exploring: "${currentNode.str}" (open: ${currentNode.open}, close: ${currentNode.close}). `;
if (currentNode.open < n) {
msg += "Can add '('. ";
nodeQueue.push(currentNode.children.find(c => c.action === 'add ('));
}
if (currentNode.close < currentNode.open) {
msg += "Can add ')'. ";
nodeQueue.push(currentNode.children.find(c => c.action === 'add )'));
}
document.getElementById('statusMessage').textContent = msg;
}
// Filter out undefined entries
nodeQueue = nodeQueue.filter(n => n !== undefined);
drawTree();
}
function autoRun() {
if (isRunning) return;
isRunning = true;
const interval = setInterval(() => {
if (nodeQueue.length === 0) {
clearInterval(interval);
isRunning = false;
document.getElementById('statusMessage').textContent =
`Complete! Found ${results.length} valid combinations: [${results.map(r => `"${r}"`).join(', ')}]`;
return;
}
step();
}, 500);
}
function renderResults() {
const container = document.getElementById('resultsContainer');
if (results.length === 0) {
container.innerHTML = '<span style="color: #999;">None yet...</span>';
return;
}
container.innerHTML = results.map((r, i) => `
<div style="padding: 8px 12px; margin: 5px 0; background: #e8f5e9;
border-radius: 6px; font-family: monospace; font-weight: bold;
color: #2e7d32;">
${i + 1}. ${r}
</div>
`).join('');
}
function reset() {
n = parseInt(document.getElementById('nValue').value);
treeData = buildFullTree();
results = [];
currentNode = null;
isRunning = false;
initQueue();
document.getElementById('statusMessage').textContent =
`Click Step to explore backtracking with n=${n}`;
document.getElementById('currentStr').textContent = '""';
document.getElementById('openCount').textContent = '0';
document.getElementById('closeCount').textContent = '0';
renderResults();
drawTree();
}
document.getElementById('nValue').addEventListener('change', reset);
reset();
window.addEventListener('resize', drawTree);
</script>
</body>
</html>