Files
illustrated-algorithm/partition-equal-subset-sum/index.html
T
2026-08-24 04:35:13 +00:00

197 lines
7.8 KiB
HTML
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<!DOCTYPE html>
<html lang="zh-Hans">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>089. 分割等和子集 – 图解</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>🟡 089. 分割等和子集 <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 = [
{input: [1,5,11,5], label: '示例1: [1,5,11,5]'},
{input: [1,2,3,5], label: '示例2: [1,2,3,5]'},
{input: [1,1], label: '示例3: [1,1]'},
];
let nums, steps, stepCtrl, target;
function buildSteps(arr) {
nums = [...arr]; steps = [];
const sum = arr.reduce((a,b) => a + b, 0);
if (sum % 2 !== 0) {
target = 0;
steps.push({stage:'done', msg:`总和=${sum}为奇数,无法等分`, dp:null, target:0, itemIdx:-1, curJ:-1});
return;
}
target = sum / 2;
const n = arr.length;
const dp = new Array(target + 1).fill(false);
dp[0] = true;
steps.push({stage:'init', msg:`总和=${sum},目标=${target},0-1背包:每件物品选或不选`, dp:[...dp], target, itemIdx:-1, curJ:-1});
for (let i = 0; i < n; i++) {
steps.push({stage:'item', msg:`考虑物品 ${i}:nums[${i}]=${arr[i]}`, dp:[...dp], target, itemIdx:i, curJ:-1});
for (let j = target; j >= arr[i]; j--) {
if (dp[j - arr[i]] && !dp[j]) {
dp[j] = true;
steps.push({stage:'fill', msg:`dp[${j}] = dp[${j}-${arr[i]}] = dp[${j-arr[i]}] = true → dp[${j}]=true`, dp:[...dp], target, itemIdx:i, curJ:j});
}
}
if (dp[target]) {
steps.push({stage:'done', msg:`已找到和为 ${target} 的子集,可以等分!`, dp:[...dp], target, itemIdx:i, curJ:target});
return;
}
}
steps.push({stage:'done', msg:`无法找到和为 ${target} 的子集`, dp:[...dp], target, itemIdx:-1, curJ:-1});
}
function render(step) {
const s = steps[step];
if (!s.dp) {
$('vizArea').innerHTML = '<div class="formula-box">总和为奇数,直接返回 false</div>';
$('detailContent').innerHTML = '<div class="calc-block">' + s.msg + '</div>';
$('resultContent').innerHTML = '<div class="final-answer" style="border-color:#f87171;background:#fef2f2;">无法等分</div>';
$('hintText').textContent = s.msg;
$('pipeline').innerHTML = '<span class="pipe-step active">完成</span>';
return;
}
let viz = '<div style="margin-top:8px;"><b>物品:</b></div>';
viz += '<div style="display:flex;gap:4px;margin:4px 0;">';
nums.forEach((v, i) => {
const cls = i === s.itemIdx ? 'orange' : (i < s.itemIdx || s.stage==='done' ? 'green' : 'default');
viz += `<span class="chip ${cls}" style="min-width:36px;">${v}</span>`;
});
viz += '</div>';
viz += `<div style="margin-top:8px;"><b>dp 表(容量 0~${s.target}):</b></div>`;
viz += '<div style="display:flex;flex-wrap:wrap;gap:3px;margin:4px 0;">';
for (let j = 0; j <= s.target; j++) {
let cls = s.dp[j] ? 'green' : 'default';
if (j === s.curJ) cls = 'orange';
viz += `<span class="chip-group"><span class="chip ${cls}" style="min-width:28px;font-size:12px;height:26px;">${s.dp[j]?'T':'F'}</span><span class="chip-index">${j}</span></span>`;
}
viz += '</div>';
$('vizArea').innerHTML = viz;
$('detailContent').innerHTML = '<div class="calc-block">' + s.msg + '</div>';
if (s.dp[s.target]) {
$('detailContent').innerHTML += `<div class="current-answer">dp[${s.target}] = <b>true</b></div>`;
}
if (s.stage === 'done') {
if (s.dp && s.dp[s.target]) {
$('resultContent').innerHTML = `<div class="final-answer">可以等分为两个子集,和各为 <b>${s.target}</b> ✅</div>`;
} else {
$('resultContent').innerHTML = '<div class="final-answer" style="border-color:#f87171;background:#fef2f2;">无法等分 ❌</div>';
}
}
$('hintText').textContent = s.msg;
const stages = ['init→初始化','item→物品','fill→填充','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 = '[1,5,11,5]';
buildSteps(examples[0].input);
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 = () => {
try { const arr = JSON.parse($('inputArea').value); buildSteps(arr); stepCtrl.setSteps(steps.map((_,i)=>i)); render(0); $('stepInfo').textContent = '步骤 1 / ' + steps.length; }
catch(e) { alert('请输入合法 JSON 数组'); }
};
$('exampleSelect').onchange = () => {
const e = examples[parseInt($('exampleSelect').value)];
$('inputArea').value = JSON.stringify(e.input);
buildSteps(e.input); 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 canPartition(nums):
total = sum(nums)
if total % 2: return False
target = total // 2
dp = [False] * (target + 1)
dp[0] = True
for num in nums:
for j in range(target, num - 1, -1):
dp[j] = dp[j] or dp[j - num]
if dp[target]: return True
return dp[target]`, {lang:'Python'});
})();
</script>
</body>
</html>