-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path0046_permutations.html
More file actions
557 lines (477 loc) · 20.4 KB
/
0046_permutations.html
File metadata and controls
557 lines (477 loc) · 20.4 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
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>LC 46: Permutations - 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">#46</span> Permutations</h1>
<p>Given an array of distinct integers, return all possible permutations. You can return them in any order.</p>
<div class="problem-meta">
<span class="meta-tag">↩️ Backtracking</span>
<span class="meta-tag">🔄 Recursion</span>
<span class="meta-tag">⏱️ O(n! × n)</span>
<span class="meta-tag">💾 O(n!)</span>
</div>
<div class="file-ref">
📄 Python: <code>python/0046_permutations/0046_permutations.py</code>
</div>
</div>
<div class="explanation-panel">
<h4>🧠 How It Works (Layman's Terms)</h4>
<p>Think of arranging people in a line - pick one for position 1, then one for position 2, and so on:</p>
<ul>
<li><strong>Choose:</strong> Pick an element for the current position</li>
<li><strong>Explore:</strong> Recursively arrange the remaining elements</li>
<li><strong>Unchoose:</strong> Backtrack and try the next element</li>
<li><strong>Base case:</strong> When no elements left, we have a complete permutation!</li>
</ul>
</div>
<div class="visualization-section">
<h3>🎬 Step-by-Step Visualization</h3>
<div class="controls">
<button class="btn btn-primary" id="stepBtn" onclick="step()">Step</button>
<button class="btn btn-success" id="autoBtn" onclick="toggleAuto()">Auto Run</button>
<button class="btn btn-warning" onclick="reset()">Reset</button>
</div>
<div class="info-box secondary" style="margin-bottom: 20px;">
📊 Input: <strong>[1, 2, 3]</strong>
</div>
<div class="status-message" id="statusMessage">
Click "Step" or "Auto Run" to start visualization
</div>
<div style="display: flex; gap: 30px; flex-wrap: wrap; margin-top: 20px;">
<div style="flex: 1; min-width: 300px;">
<div class="array-section">
<div class="array-label">🔢 Available Numbers:</div>
<div class="array-container" id="availableContainer"></div>
</div>
<div class="array-section" style="margin-top: 15px;">
<div class="array-label">📝 Current Path:</div>
<div class="array-container" id="pathContainer"></div>
</div>
<div class="explanation-panel" style="margin-top: 15px;">
<h4>📚 Recursion Stack</h4>
<div id="stackContainer" style="display: flex; flex-direction: column-reverse; gap: 5px; padding: 10px;">
<span style="color: #666;">Empty</span>
</div>
</div>
</div>
<div style="flex: 1; min-width: 300px;">
<div class="array-section">
<div class="array-label">✅ Found Permutations:</div>
<div id="resultContainer" style="display: flex; flex-direction: column; gap: 8px; padding: 10px; background: #f5f5f5; border-radius: 8px; min-height: 200px;">
<span style="color: #666;">None yet...</span>
</div>
</div>
</div>
</div>
<div id="treeContainer" style="width: 100%; height: 300px; margin-top: 20px; overflow-x: auto;"></div>
</div>
<div class="code-section">
<h3>💻 Python Solution</h3>
<div class="code-block">
<pre>from typing import List
"""
LeetCode Permutations
Problem from LeetCode: https://leetcode.com/problems/permutations/
Description:
Given an array nums of distinct integers, return all the possible permutations. You can return the answer in any order.
Example 1:
Input: nums = [1,2,3]
Output: [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
Example 2:
Input: nums = [0,1]
Output: [[0,1],[1,0]]
Example 3:
Input: nums = [1]
Output: [[1]]
"""
class Solution:
def permute(self, nums: List[int]) -> List[List[int]]:
"""
Generate all possible permutations of an array of distinct integers.
Uses backtracking approach.
Args:
nums: Array of distinct integers
Returns:
List[List[int]]: All possible permutations
"""
result = []
self._backtrack(nums, [], result)
return result
def _backtrack(self, nums: List[int], path: List[int], result: List[List[int]]) -> None:
"""
Helper function for backtracking.
Args:
nums: Remaining integers to permute
path: Current permutation being built
result: List to collect all permutations
"""
# If no numbers left, we've completed a permutation
if not nums:
result.append(path)
return
for i in range(len(nums)):
# Choose the current number and recurse
self._backtrack(nums[:i] + nums[i+1:], path + [nums[i]], result)
def permute_iterative(self, nums: List[int]) -> List[List[int]]:
"""
Generate all permutations using an iterative approach.
Args:
nums: Array of distinct integers
Returns:
List[List[int]]: All possible permutations
"""
# Start with an empty permutation
result = [[]]
for num in nums:
new_perms = []
for perm in result:
# Insert the current number at each possible position
for i in range(len(perm) + 1):
new_perms.append(perm[:i] + [num] + perm[i:])
result = new_perms
return result
def permute_swap(self, nums: List[int]) -> List[List[int]]:
"""
Generate permutations by swapping elements in-place.
Args:
nums: Array of distinct integers
Returns:
List[List[int]]: All possible permutations
"""
result = []
def backtrack(start):
if start == len(nums):
result.append(nums[:]) # Make a copy of the current state
return
for i in range(start, len(nums)):
# Swap elements
nums[start], nums[i] = nums[i], nums[start]
# Recurse on the next position
backtrack(start + 1)
# Backtrack (undo the swap)
nums[start], nums[i] = nums[i], nums[start]
backtrack(0)
return result
if __name__ == '__main__':
# Example usage based on LeetCode sample
solution = Solution()
# Example 1
nums1 = [1, 2, 3]
result1 = solution.permute(nums1)
print(f"Example 1: {result1}")
# Expected output: [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
# Example 2
nums2 = [0, 1]
result2 = solution.permute(nums2)
print(f"Example 2: {result2}")
# Expected output: [[0,1],[1,0]]
# Example 3
nums3 = [1]
result3 = solution.permute(nums3)
print(f"Example 3: {result3}")
# Expected output: [[1]]
# Compare with other implementations
print("\nUsing iterative approach:")
print(f"Example 1: {solution.permute_iterative(nums1)}")
print("\nUsing swap approach:")
print(f"Example 1: {solution.permute_swap(nums1)}")
</pre>
</div>
</div>
</div>
<script>
const originalNums = [1, 2, 3];
let steps = [];
let currentStepIdx = -1;
let results = [];
let autoInterval = null;
// Pre-generate all steps
function generateSteps() {
steps = [];
results = [];
function backtrack(nums, path, depth) {
steps.push({
type: 'enter',
nums: [...nums],
path: [...path],
depth,
message: nums.length === 0 ?
`✅ Complete permutation found: [${path.join(', ')}]` :
`Entering with available: [${nums.join(', ')}], path: [${path.join(', ')}]`
});
if (nums.length === 0) {
results.push([...path]);
steps.push({
type: 'found',
nums: [],
path: [...path],
depth,
results: results.length,
message: `Added permutation #${results.length}: [${path.join(', ')}]`
});
return;
}
for (let i = 0; i < nums.length; i++) {
steps.push({
type: 'choose',
nums: [...nums],
path: [...path],
chosen: nums[i],
chosenIdx: i,
depth,
message: `Choosing ${nums[i]} (option ${i + 1} of ${nums.length})`
});
const newNums = [...nums.slice(0, i), ...nums.slice(i + 1)];
const newPath = [...path, nums[i]];
backtrack(newNums, newPath, depth + 1);
steps.push({
type: 'backtrack',
nums: [...nums],
path: [...path],
unchosen: nums[i],
depth,
message: `Backtracking: undo choosing ${nums[i]}`
});
}
}
backtrack(originalNums, [], 0);
}
function init() {
generateSteps();
renderState(originalNums, []);
renderTree();
}
function renderState(available, path) {
// Available numbers
const availContainer = document.getElementById('availableContainer');
availContainer.innerHTML = '';
if (available.length === 0) {
availContainer.innerHTML = '<span style="color: #4caf50; padding: 10px;">Empty (complete!)</span>';
} else {
available.forEach((num, i) => {
const box = document.createElement('div');
box.className = 'array-box';
box.textContent = num;
box.style.background = '#fff3e0';
box.style.borderColor = '#ff9800';
availContainer.appendChild(box);
});
}
// Current path
const pathContainer = document.getElementById('pathContainer');
pathContainer.innerHTML = '';
if (path.length === 0) {
pathContainer.innerHTML = '<span style="color: #666; padding: 10px;">Empty</span>';
} else {
path.forEach((num) => {
const box = document.createElement('div');
box.className = 'array-box';
box.textContent = num;
box.style.background = '#c8e6c9';
box.style.borderColor = '#4caf50';
pathContainer.appendChild(box);
});
}
}
function renderStack() {
const container = document.getElementById('stackContainer');
// Build current stack from steps
const stack = [];
for (let i = 0; i <= currentStepIdx; i++) {
const s = steps[i];
if (s.type === 'enter') {
stack.push({path: s.path, nums: s.nums});
} else if (s.type === 'backtrack') {
stack.pop();
}
}
if (stack.length === 0) {
container.innerHTML = '<span style="color: #666;">Empty</span>';
return;
}
container.innerHTML = stack.map((frame, i) =>
`<div style="padding: 8px 12px; background: ${i === stack.length - 1 ? '#667eea' : '#e0e0e0'};
color: ${i === stack.length - 1 ? 'white' : '#333'}; border-radius: 5px; font-size: 0.9em;">
path: [${frame.path.join(', ')}], available: [${frame.nums.join(', ')}]
</div>`
).join('');
}
function renderResults() {
const container = document.getElementById('resultContainer');
// Count results found so far
let foundCount = 0;
const foundPerms = [];
for (let i = 0; i <= currentStepIdx; i++) {
if (steps[i].type === 'found') {
foundPerms.push(steps[i].path);
}
}
if (foundPerms.length === 0) {
container.innerHTML = '<span style="color: #666;">None yet...</span>';
return;
}
container.innerHTML = foundPerms.map((perm, i) =>
`<div style="padding: 8px 12px; background: #c8e6c9; border-radius: 5px; font-weight: bold;">
${i + 1}. [${perm.join(', ')}]
</div>`
).join('');
}
function renderTree() {
const container = document.getElementById('treeContainer');
d3.select('#treeContainer').selectAll('*').remove();
const width = Math.max(container.offsetWidth, 700);
const height = 280;
const svg = d3.select('#treeContainer')
.append('svg')
.attr('width', width)
.attr('height', height);
// Build tree structure
const treeData = {
name: '[1,2,3]',
path: [],
children: [
{
name: '1',
path: [1],
children: [
{name: '2', path: [1,2], children: [{name: '3', path: [1,2,3], children: []}]},
{name: '3', path: [1,3], children: [{name: '2', path: [1,3,2], children: []}]}
]
},
{
name: '2',
path: [2],
children: [
{name: '1', path: [2,1], children: [{name: '3', path: [2,1,3], children: []}]},
{name: '3', path: [2,3], children: [{name: '1', path: [2,3,1], children: []}]}
]
},
{
name: '3',
path: [3],
children: [
{name: '1', path: [3,1], children: [{name: '2', path: [3,1,2], children: []}]},
{name: '2', path: [3,2], children: [{name: '1', path: [3,2,1], children: []}]}
]
}
]
};
const hierarchy = d3.hierarchy(treeData);
const treeLayout = d3.tree().size([width - 60, height - 80]);
treeLayout(hierarchy);
// Get current path from steps
let currentPath = [];
if (currentStepIdx >= 0) {
currentPath = steps[currentStepIdx].path || [];
}
// Links
svg.selectAll('.link')
.data(hierarchy.links())
.enter()
.append('line')
.attr('class', 'link')
.attr('x1', d => d.source.x + 30)
.attr('y1', d => d.source.y + 25)
.attr('x2', d => d.target.x + 30)
.attr('y2', d => d.target.y + 25)
.attr('stroke', '#ccc')
.attr('stroke-width', 2);
// Nodes
const nodes = svg.selectAll('.node')
.data(hierarchy.descendants())
.enter()
.append('g')
.attr('class', 'node')
.attr('transform', d => `translate(${d.x + 30}, ${d.y + 25})`);
nodes.append('circle')
.attr('r', 18)
.attr('fill', d => {
const nodePath = d.data.path;
const pathStr = nodePath.join(',');
const currStr = currentPath.join(',');
if (pathStr === currStr && currentPath.length > 0) return '#667eea';
if (currStr.startsWith(pathStr) && pathStr.length > 0) return '#bbdefb';
if (nodePath.length === 3) {
// Check if this permutation has been found
for (let i = 0; i <= currentStepIdx; i++) {
if (steps[i].type === 'found' && steps[i].path.join(',') === pathStr) {
return '#4caf50';
}
}
}
return '#fff';
})
.attr('stroke', '#667eea')
.attr('stroke-width', 2);
nodes.append('text')
.attr('text-anchor', 'middle')
.attr('dy', 5)
.attr('font-size', '12px')
.attr('font-weight', 'bold')
.attr('fill', d => {
const nodePath = d.data.path;
const currStr = currentPath.join(',');
if (nodePath.join(',') === currStr && currentPath.length > 0) return '#fff';
return '#333';
})
.text(d => d.data.name);
}
function step() {
currentStepIdx++;
if (currentStepIdx >= steps.length) {
document.getElementById('statusMessage').className = 'status-message success';
document.getElementById('statusMessage').textContent =
`✅ Complete! Found all ${results.length} permutations.`;
document.getElementById('stepBtn').disabled = true;
stopAuto();
return;
}
const s = steps[currentStepIdx];
document.getElementById('statusMessage').textContent = s.message;
renderState(s.nums, s.path);
renderStack();
renderResults();
renderTree();
}
function toggleAuto() {
if (autoInterval) {
stopAuto();
} else {
document.getElementById('autoBtn').textContent = 'Pause';
autoInterval = setInterval(() => {
if (currentStepIdx >= steps.length - 1) {
step();
stopAuto();
} else {
step();
}
}, 600);
}
}
function stopAuto() {
if (autoInterval) {
clearInterval(autoInterval);
autoInterval = null;
}
document.getElementById('autoBtn').textContent = 'Auto Run';
}
function reset() {
stopAuto();
currentStepIdx = -1;
document.getElementById('stepBtn').disabled = false;
document.getElementById('statusMessage').className = 'status-message';
document.getElementById('statusMessage').textContent = 'Click "Step" or "Auto Run" to start visualization';
init();
}
init();
</script>
</body>
</html>