180 lines
7.6 KiB
HTML
180 lines
7.6 KiB
HTML
<!DOCTYPE html>
|
||
<html lang="zh-Hans">
|
||
<head>
|
||
<meta charset="UTF-8">
|
||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||
<title>058. 组合总和 – 图解</title>
|
||
<link rel="stylesheet" href="../shared/style.css">
|
||
<style>
|
||
/* page-specific overrides */
|
||
.vis-area { min-height: 120px; padding: 16px 0; }
|
||
.code-section { margin-top: 16px; }
|
||
</style>
|
||
</head>
|
||
<body>
|
||
<div class="container">
|
||
<h1>🟡 058. 组合总和 <span class="badge medium">中等</span></h1>
|
||
<p class="subtitle">分类:回溯 | LeetCode Hot 100</p>
|
||
|
||
<!-- 控制面板 -->
|
||
<div class="controls" id="controls">
|
||
<label for="inputArea">输入:</label>
|
||
<input type="text" id="inputArea" placeholder="默认示例,可自定义">
|
||
<button id="applyBtn" class="primary">生成图解</button>
|
||
<select id="exampleSelect"></select>
|
||
<span style="flex:1"></span>
|
||
<button id="prevBtn">◀ 上一步</button>
|
||
<button id="nextBtn">下一步 ▶</button>
|
||
<button id="jumpBtn">⏭ 跳到结果</button>
|
||
<button id="autoBtn">自动播放</button>
|
||
<button id="resetBtn">重置</button>
|
||
</div>
|
||
|
||
<!-- 步骤流水线 -->
|
||
<div class="pipeline" id="pipeline"></div>
|
||
|
||
<!-- 提示条 -->
|
||
<div class="hint info" id="hintBox">
|
||
<span id="stepInfo"></span><br>
|
||
<span id="hintText"></span>
|
||
</div>
|
||
|
||
<!-- 可视化面板 -->
|
||
<div class="panels">
|
||
<div class="panel" id="mainPanel">
|
||
<h3>📊 可视化</h3>
|
||
<div class="vis-area" id="vizArea">点击「生成图解」开始</div>
|
||
</div>
|
||
<div class="panel-grid">
|
||
<div class="panel" id="detailPanel">
|
||
<h3>📝 当前步骤详情</h3>
|
||
<div id="detailContent">等待开始...</div>
|
||
</div>
|
||
<div class="panel" id="resultPanel">
|
||
<h3>✅ 结果</h3>
|
||
<div id="resultContent">等待完成...</div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
|
||
<!-- 代码 -->
|
||
<div class="panel code-section">
|
||
<h3>💻 参考代码(Python)</h3>
|
||
<div id="codeArea"></div>
|
||
</div>
|
||
|
||
<footer>Powered by QwenPaw · 图解算法 · LeetCode Hot 100</footer>
|
||
</div>
|
||
|
||
<script src="../shared/algo-viz.js"></script>
|
||
<script>
|
||
"use strict";
|
||
(function() {
|
||
// ========== Algorithm Logic ==========
|
||
|
||
const examples = [
|
||
{candidates: [2,3,6,7], target: 7, label: '示例1: [2,3,6,7] target=7'},
|
||
{candidates: [2,3,5], target: 8, label: '示例2: [2,3,5] target=8'},
|
||
{candidates: [2], target: 1, label: '示例3: [2] target=1'},
|
||
];
|
||
let cands, target, steps, stepCtrl;
|
||
|
||
function buildSteps(arr, tgt) {
|
||
cands = [...arr].sort((a,b)=>a-b); target = tgt; steps = [];
|
||
const result = [];
|
||
const path = [];
|
||
|
||
steps.push({stage:'start', msg:`排序后: [${cands}], 目标: ${tgt}`, path:[], sum:0, remain:tgt, start:0, result:[]});
|
||
|
||
function backtrack(start, sum) {
|
||
if (sum === target) {
|
||
result.push([...path]);
|
||
steps.push({stage:'found', msg:`和=${target},找到组合 [${path}]`, path:[...path], sum, remain:0, start, result:JSON.parse(JSON.stringify(result))});
|
||
return;
|
||
}
|
||
for (let i = start; i < cands.length; i++) {
|
||
if (sum + cands[i] > target) {
|
||
steps.push({stage:'prune', msg:`${sum}+${cands[i]}=${sum+cands[i]} > ${target},剪枝 ✂️`, path:[...path], sum, remain:target-sum, start:i, result:JSON.parse(JSON.stringify(result))});
|
||
break; // sorted, so all following are larger
|
||
}
|
||
path.push(cands[i]);
|
||
steps.push({stage:'choose', msg:`选择 ${cands[i]},sum=${sum}+${cands[i]}=${sum+cands[i]},remain=${target-sum-cands[i]}`, path:[...path], sum:sum+cands[i], remain:target-sum-cands[i], start:i, result:JSON.parse(JSON.stringify(result))});
|
||
backtrack(i, sum + cands[i]);
|
||
path.pop();
|
||
steps.push({stage:'undo', msg:`回溯:移除 ${cands[i]}`, path:[...path], sum, remain:target-sum, start:i, result:JSON.parse(JSON.stringify(result))});
|
||
}
|
||
}
|
||
backtrack(0, 0);
|
||
steps.push({stage:'done', msg:`共 ${result.length} 个组合`, path:[], sum:0, remain:target, start:-1, result:JSON.parse(JSON.stringify(result))});
|
||
}
|
||
|
||
function render(step) {
|
||
const s = steps[step];
|
||
const hl = {};
|
||
if (s.start >= 0) for (let i=s.start; i<cands.length; i++) hl[i] = i===s.start?'orange':'default';
|
||
let viz = '<div style="margin-bottom:8px;"><b>候选数:</b></div>';
|
||
viz += renderArray(cands, {highlights:hl});
|
||
viz += `<div style="margin-top:10px;display:flex;gap:16px;">
|
||
<span><b>当前组合:</b><span class="chip purple" style="min-width:auto;padding:2px 10px;">[${s.path.join(', ')}]</span></span>
|
||
<span><b>sum:</b>${s.sum}</span>
|
||
<span><b>remain:</b><span style="color:${s.remain===0?'var(--green)':'var(--blue)'};">${s.remain}</span></span>
|
||
</div>`;
|
||
if (s.result.length > 0) {
|
||
viz += '<div style="margin-top:8px;"><b>已找到:</b></div><div style="display:flex;flex-wrap:wrap;gap:4px;">';
|
||
s.result.forEach(r => { viz += `<span class="chip green" style="min-width:auto;padding:2px 8px;font-size:12px;">[${r.join(',')}]</span>`; });
|
||
viz += '</div>';
|
||
}
|
||
$('vizArea').innerHTML = viz;
|
||
$('detailContent').innerHTML = '<div class="calc-block">' + s.msg + '</div>';
|
||
if (s.stage==='done') $('resultContent').innerHTML = `<div class="final-answer">共 <b>${s.result.length}</b> 个组合</div>`;
|
||
$('hintText').textContent = s.msg;
|
||
const stages = ['start→开始','choose→选择','found→找到','prune→剪枝','undo→回溯','done→完成'];
|
||
$('pipeline').innerHTML = stages.map(st => { const [k,l]=st.split('→'); return `<span class="pipe-step ${s.stage===k?'active':''}">${l}</span>`; }).join('<i>→</i>');
|
||
}
|
||
|
||
function init() {
|
||
const sel = $('exampleSelect');
|
||
examples.forEach((e,i) => { sel.innerHTML += `<option value="${i}">${e.label}</option>`; });
|
||
$('inputArea').value = '[2,3,6,7], target=7';
|
||
buildSteps(examples[0].candidates, examples[0].target);
|
||
stepCtrl = new StepController({onStep: render});
|
||
stepCtrl.setSteps(steps.map((_,i)=>i));
|
||
$('stepInfo').textContent = '步骤 1 / ' + steps.length;
|
||
stepCtrl.onStep = (idx) => { render(idx); $('stepInfo').textContent = `步骤 ${idx+1} / ${steps.length}`; };
|
||
$('applyBtn').onclick = () => {
|
||
const m = $('inputArea').value.match(/\[([^\]]+)\].*?(\d+)/);
|
||
if (!m) { alert('格式: [2,3,6,7], target=7'); return; }
|
||
const arr = m[1].split(',').map(Number);
|
||
buildSteps(arr, parseInt(m[2])); stepCtrl.setSteps(steps.map((_,i)=>i)); render(0); $('stepInfo').textContent = '步骤 1 / ' + steps.length;
|
||
};
|
||
$('exampleSelect').onchange = () => {
|
||
const e = examples[parseInt($('exampleSelect').value)];
|
||
buildSteps(e.candidates, e.target); stepCtrl.setSteps(steps.map((_,i)=>i)); render(0);
|
||
};
|
||
$('prevBtn').onclick = () => stepCtrl.prev();
|
||
$('nextBtn').onclick = () => stepCtrl.next();
|
||
$('jumpBtn').onclick = () => stepCtrl.jumpToEnd();
|
||
$('autoBtn').onclick = () => { const on = stepCtrl.toggleAuto(); $('autoBtn').textContent = on ? '暂停' : '自动播放'; };
|
||
$('resetBtn').onclick = () => { stepCtrl.reset(); $('autoBtn').textContent = '自动播放'; };
|
||
}
|
||
init();
|
||
$('codeArea').innerHTML = renderCode(`def combinationSum(candidates, target):
|
||
candidates.sort()
|
||
res = []
|
||
def backtrack(start, path, remaining):
|
||
if remaining == 0:
|
||
res.append(path[:])
|
||
return
|
||
for i in range(start, len(candidates)):
|
||
if candidates[i] > remaining:
|
||
break # 剪枝
|
||
path.append(candidates[i])
|
||
backtrack(i, path, remaining - candidates[i])
|
||
path.pop()
|
||
backtrack(0, [], target)
|
||
return res`, {lang:'Python'});
|
||
|
||
})();
|
||
</script>
|
||
</body>
|
||
</html> |