-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path0039_combination_sum.html
More file actions
606 lines (523 loc) · 22 KB
/
0039_combination_sum.html
File metadata and controls
606 lines (523 loc) · 22 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
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>39 - Combination Sum</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">#39</span> Combination Sum</h1>
<p>
Given an array of distinct integers and a target, find all unique combinations
where the numbers sum to target. The same number may be used unlimited times.
</p>
<div class="problem-meta">
<span class="meta-tag">📊 Array</span>
<span class="meta-tag">🔄 Backtracking</span>
<span class="meta-tag">⏱️ O(2ⁿ)</span>
</div>
<div class="file-ref">
📄 Python: <code>python/0039_combination_sum/0039_combination_sum.py</code>
</div>
<h3>Example:</h3>
<pre>
candidates = [2, 3, 6, 7], target = 7
Output: [[2,2,3], [7]]
</pre>
</div>
<div class="explanation-panel">
<h4>🧠 How It Works (Layman's Terms)</h4>
<p>Backtracking <strong>explores all possibilities</strong> like solving a maze:</p>
<ul>
<li><strong>Choose:</strong> Make a decision</li>
<li><strong>Explore:</strong> Recursively continue</li>
<li><strong>Validate:</strong> Check if path is valid</li>
<li><strong>Backtrack:</strong> Undo choice if stuck, try another</li>
</ul>
</div>
<section class="visualization-section">
<h3>🎬 Step-by-Step Visualization</h3>
<div class="controls">
<button id="stepBtn" class="btn">Step</button>
<button id="autoBtn" class="btn btn-success">Auto Run</button>
<button id="resetBtn" class="btn btn-danger">Reset</button>
</div>
<div class="status" id="status">Find all combinations that sum to target</div>
<svg id="visualization"></svg>
</section>
<section class="code-section">
<h3>💻 Python Solution</h3>
<div class="code-block">
<pre>from typing import List
"""
LeetCode Combination Sum
Problem from LeetCode: https://leetcode.com/problems/combination-sum/
Description:
Given an array of distinct integers candidates and a target integer target, return a list of all unique combinations of candidates where the chosen numbers sum to target. You may return the combinations in any order.
The same number may be chosen from candidates an unlimited number of times. Two combinations are unique if the frequency of at least one of the chosen numbers is different.
It is guaranteed that the number of unique combinations that sum up to target is less than 150 combinations for the given input.
Example 1:
Input: candidates = [2,3,6,7], target = 7
Output: [[2,2,3],[7]]
Explanation:
2 and 3 are candidates, and 2 + 2 + 3 = 7. Note that 2 can be used multiple times.
7 is a candidate, and 7 = 7.
These are the only two combinations.
Example 2:
Input: candidates = [2,3,5], target = 8
Output: [[2,2,2,2],[2,3,3],[3,5]]
Example 3:
Input: candidates = [2], target = 1
Output: []
"""
class Solution:
def combination_sum(self, candidates: List[int], target: int) -> List[List[int]]:
"""
Find all unique combinations of numbers that sum to target.
Uses backtracking approach.
Args:
candidates: Array of distinct integers
target: Target sum
Returns:
List[List[int]]: All unique combinations that sum to target
"""
result = []
self._backtrack(candidates, target, [], result, 0)
return result
def _backtrack(self, candidates: List[int], target: int, path: List[int], result: List[List[int]], start: int) -> None:
"""
Helper function for backtracking.
Args:
candidates: Available numbers
target: Remaining target sum
path: Current combination being built
result: List to collect valid combinations
start: Starting index to avoid duplicates
"""
if target < 0:
return
if target == 0:
result.append(path[:])
return
for i in range(start, len(candidates)):
path.append(candidates[i])
# Continue from the same index since we can reuse the same element
self._backtrack(candidates, target - candidates[i], path, result, i)
path.pop() # Backtrack
def combination_sum_iterative(self, candidates: List[int], target: int) -> List[List[int]]:
"""
Iterative approach using a queue-like structure.
Args:
candidates: Array of distinct integers
target: Target sum
Returns:
List[List[int]]: All unique combinations that sum to target
"""
result = []
# Sort to optimize and handle smaller candidates first
candidates.sort()
# Queue of (combination, target_remaining, start_index)
queue = [([], target, 0)]
while queue:
path, remain, start = queue.pop(0)
if remain == 0:
result.append(path)
continue
for i in range(start, len(candidates)):
# Skip if this candidate is too large
if candidates[i] > remain:
break
# Skip duplicates (unnecessary for distinct candidates but useful for extension)
if i > start and candidates[i] == candidates[i-1]:
continue
# Add this candidate and continue
new_path = path + [candidates[i]]
queue.append((new_path, remain - candidates[i], i)) # i to reuse the same element
return result
if __name__ == '__main__':
# Example usage based on LeetCode sample
solution = Solution()
# Example 1
candidates1 = [2, 3, 6, 7]
target1 = 7
result1 = solution.combination_sum(candidates1, target1)
print(f"Example 1: candidates={candidates1}, target={target1}")
print(f"Result: {result1}") # Expected output: [[2,2,3],[7]]
# Example 2
candidates2 = [2, 3, 5]
target2 = 8
result2 = solution.combination_sum(candidates2, target2)
print(f"\nExample 2: candidates={candidates2}, target={target2}")
print(f"Result: {result2}") # Expected output: [[2,2,2,2],[2,3,3],[3,5]]
# Example 3
candidates3 = [2]
target3 = 1
result3 = solution.combination_sum(candidates3, target3)
print(f"\nExample 3: candidates={candidates3}, target={target3}")
print(f"Result: {result3}") # Expected output: []
# Compare with iterative approach
print("\nUsing iterative approach:")
print(f"Example 1: {solution.combination_sum_iterative(candidates1, target1)}")
print(f"Example 2: {solution.combination_sum_iterative(candidates2, target2)}")
</pre>
</div>
</section>
</div>
<script>
const width = 900;
const height = 650;
const svg = d3.select("#visualization")
.attr("width", width)
.attr("height", height);
const candidates = [2, 3, 6, 7];
const target = 7;
let treeNodes = [];
let treeEdges = [];
let currentPath = [];
let results = [];
let stack = [];
let isRunning = false;
let phase = "init";
let nodeId = 0;
function reset() {
treeNodes = [];
treeEdges = [];
currentPath = [];
results = [];
stack = [{ start: 0, path: [], remaining: target, parentId: null }];
phase = "init";
nodeId = 0;
isRunning = false;
document.getElementById("autoBtn").textContent = "Auto Run";
document.getElementById("status").textContent =
`Find combinations from [${candidates.join(', ')}] that sum to ${target}`;
render();
}
function render() {
svg.selectAll("*").remove();
const startX = 50;
// Candidates display
svg.append("text")
.attr("x", startX)
.attr("y", 30)
.attr("font-size", "14px")
.attr("font-weight", "bold")
.attr("fill", "#1e293b")
.text("Candidates:");
candidates.forEach((c, idx) => {
const x = startX + 100 + idx * 60;
svg.append("rect")
.attr("x", x)
.attr("y", 10)
.attr("width", 50)
.attr("height", 35)
.attr("rx", 6)
.attr("fill", "#dbeafe")
.attr("stroke", "#3b82f6");
svg.append("text")
.attr("x", x + 25)
.attr("y", 33)
.attr("text-anchor", "middle")
.attr("font-size", "16px")
.attr("font-weight", "bold")
.attr("fill", "#1e293b")
.text(c);
});
svg.append("text")
.attr("x", startX + 380)
.attr("y", 33)
.attr("font-size", "14px")
.attr("fill", "#64748b")
.text(`Target: ${target}`);
// Current path
svg.append("text")
.attr("x", startX)
.attr("y", 70)
.attr("font-size", "14px")
.attr("font-weight", "bold")
.attr("fill", "#1e293b")
.text(`Current path: [${currentPath.join(', ')}]`);
const pathSum = currentPath.reduce((a, b) => a + b, 0);
svg.append("text")
.attr("x", startX + 250)
.attr("y", 70)
.attr("font-size", "14px")
.attr("fill", pathSum === target ? "#10b981" : "#64748b")
.text(`Sum: ${pathSum}, Remaining: ${target - pathSum}`);
// Decision tree
const treeStartY = 100;
const levelHeight = 80;
// Draw edges first
treeEdges.forEach(edge => {
const parent = treeNodes.find(n => n.id === edge.from);
const child = treeNodes.find(n => n.id === edge.to);
if (parent && child) {
svg.append("line")
.attr("x1", parent.x)
.attr("y1", parent.y + 20)
.attr("x2", child.x)
.attr("y2", child.y - 20)
.attr("stroke", child.isResult ? "#10b981" : child.isPruned ? "#ef4444" : "#94a3b8")
.attr("stroke-width", 2);
// Edge label
svg.append("text")
.attr("x", (parent.x + child.x) / 2 + 10)
.attr("y", (parent.y + child.y) / 2)
.attr("font-size", "11px")
.attr("fill", "#64748b")
.text(`+${edge.value}`);
}
});
// Draw nodes
treeNodes.forEach(node => {
svg.append("circle")
.attr("cx", node.x)
.attr("cy", node.y)
.attr("r", 22)
.attr("fill", () => {
if (node.isResult) return "#d1fae5";
if (node.isPruned) return "#fee2e2";
if (node.isCurrent) return "#fef3c7";
return "#f8fafc";
})
.attr("stroke", () => {
if (node.isResult) return "#10b981";
if (node.isPruned) return "#ef4444";
if (node.isCurrent) return "#f59e0b";
return "#94a3b8";
})
.attr("stroke-width", node.isCurrent ? 3 : 2);
svg.append("text")
.attr("x", node.x)
.attr("y", node.y + 5)
.attr("text-anchor", "middle")
.attr("font-size", "12px")
.attr("font-weight", "bold")
.attr("fill", "#1e293b")
.text(node.remaining);
// Result/pruned indicator
if (node.isResult) {
svg.append("text")
.attr("x", node.x)
.attr("y", node.y + 38)
.attr("text-anchor", "middle")
.attr("font-size", "10px")
.attr("fill", "#10b981")
.text("✓ Found!");
}
if (node.isPruned) {
svg.append("text")
.attr("x", node.x)
.attr("y", node.y + 38)
.attr("text-anchor", "middle")
.attr("font-size", "10px")
.attr("fill", "#ef4444")
.text("✗ Prune");
}
});
// Results display
const resultsY = 480;
svg.append("text")
.attr("x", startX)
.attr("y", resultsY)
.attr("font-size", "14px")
.attr("font-weight", "bold")
.attr("fill", "#1e293b")
.text("Valid Combinations Found:");
results.forEach((result, idx) => {
const x = startX + idx * 150;
svg.append("rect")
.attr("x", x)
.attr("y", resultsY + 15)
.attr("width", 140)
.attr("height", 35)
.attr("rx", 8)
.attr("fill", "#d1fae5")
.attr("stroke", "#10b981");
svg.append("text")
.attr("x", x + 70)
.attr("y", resultsY + 38)
.attr("text-anchor", "middle")
.attr("font-size", "14px")
.attr("font-weight", "bold")
.attr("fill", "#1e293b")
.text(`[${result.join(', ')}]`);
});
// Legend
const legendX = 600;
svg.append("text")
.attr("x", legendX)
.attr("y", resultsY)
.attr("font-size", "12px")
.attr("fill", "#64748b")
.text("Node value = remaining target");
svg.append("text")
.attr("x", legendX)
.attr("y", resultsY + 20)
.attr("font-size", "12px")
.attr("fill", "#64748b")
.text("0 = found valid combination");
svg.append("text")
.attr("x", legendX)
.attr("y", resultsY + 40)
.attr("font-size", "12px")
.attr("fill", "#64748b")
.text("< 0 = pruned (exceeded target)");
// Final result
if (phase === "done") {
svg.append("rect")
.attr("x", startX)
.attr("y", 570)
.attr("width", 450)
.attr("height", 55)
.attr("rx", 10)
.attr("fill", "#d1fae5")
.attr("stroke", "#10b981")
.attr("stroke-width", 2);
svg.append("text")
.attr("x", startX + 225)
.attr("y", 605)
.attr("text-anchor", "middle")
.attr("font-size", "18px")
.attr("font-weight", "bold")
.attr("fill", "#10b981")
.text(`✓ Found ${results.length} combinations!`);
}
}
function getNodeX(level, index, totalAtLevel) {
const levelWidth = 800;
const spacing = levelWidth / (totalAtLevel + 1);
return 50 + spacing * (index + 1);
}
function step() {
if (phase === "done") return;
if (phase === "init") {
// Add root node
const rootNode = {
id: nodeId++,
x: 450,
y: 120,
remaining: target,
isCurrent: true,
isResult: false,
isPruned: false
};
treeNodes.push(rootNode);
phase = "explore";
document.getElementById("status").textContent =
`Start: remaining = ${target}, explore candidates`;
render();
return;
}
if (phase === "explore") {
if (stack.length === 0) {
phase = "done";
document.getElementById("status").textContent =
`✓ Search complete! Found ${results.length} combinations.`;
render();
return;
}
const current = stack.pop();
currentPath = current.path;
// Mark previous current node as not current
treeNodes.forEach(n => n.isCurrent = false);
if (current.remaining === 0) {
// Found a valid combination
results.push([...current.path]);
// Find and mark the current node as result
if (current.nodeId !== undefined) {
const node = treeNodes.find(n => n.id === current.nodeId);
if (node) {
node.isResult = true;
node.isCurrent = true;
}
}
document.getElementById("status").textContent =
`✓ Found: [${current.path.join(', ')}] = ${target}!`;
render();
return;
}
if (current.remaining < 0) {
// Exceeded target, prune
if (current.nodeId !== undefined) {
const node = treeNodes.find(n => n.id === current.nodeId);
if (node) {
node.isPruned = true;
node.isCurrent = true;
}
}
document.getElementById("status").textContent =
`✗ Pruned: [${current.path.join(', ')}] exceeds target`;
render();
return;
}
// Mark current node
if (current.nodeId !== undefined) {
const node = treeNodes.find(n => n.id === current.nodeId);
if (node) node.isCurrent = true;
}
// Expand: add children in reverse order so they get processed in order
const children = [];
for (let i = candidates.length - 1; i >= current.start; i--) {
const newPath = [...current.path, candidates[i]];
const newRemaining = current.remaining - candidates[i];
// Create child node
const childNode = {
id: nodeId++,
x: 0, // Will be calculated
y: 120 + (current.path.length + 1) * 70,
remaining: newRemaining,
isCurrent: false,
isResult: false,
isPruned: false
};
// Position nodes based on level
const nodesAtLevel = treeNodes.filter(n => n.y === childNode.y).length;
childNode.x = 100 + nodesAtLevel * 100;
treeNodes.push(childNode);
if (current.nodeId !== undefined || current.parentId === null) {
treeEdges.push({
from: current.nodeId !== undefined ? current.nodeId : 0,
to: childNode.id,
value: candidates[i]
});
}
stack.push({
start: i,
path: newPath,
remaining: newRemaining,
parentId: current.nodeId,
nodeId: childNode.id
});
}
document.getElementById("status").textContent =
`Exploring: [${current.path.join(', ')}], remaining = ${current.remaining}`;
render();
}
}
async function autoRun() {
if (isRunning) {
isRunning = false;
document.getElementById("autoBtn").textContent = "Auto Run";
return;
}
isRunning = true;
document.getElementById("autoBtn").textContent = "Pause";
while (phase !== "done" && isRunning) {
step();
await new Promise(r => setTimeout(r, 300));
}
isRunning = false;
document.getElementById("autoBtn").textContent = "Auto Run";
}
document.getElementById("stepBtn").addEventListener("click", step);
document.getElementById("autoBtn").addEventListener("click", autoRun);
document.getElementById("resetBtn").addEventListener("click", reset);
reset();
</script>
</body>
</html>