Files
2026-08-24 04:35:13 +00:00

181 lines
7.1 KiB
HTML
Raw Permalink 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>084. 完全平方数 – 图解</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>🟡 084. 完全平方数 <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: 12, label: '示例1: n=12'},
{input: 13, label: '示例2: n=13'},
{input: 4, label: '示例3: n=4'},
];
let steps, stepCtrl, n;
function buildSteps(target) {
n = target; steps = [];
const dp = new Array(n + 1).fill(Infinity);
dp[0] = 0;
steps.push({stage:'init', msg:`初始化 dp[0]=0,其余为 ∞`, dp:[...dp], current:-1, bestJ:-1, candidates:[]});
for (let i = 1; i <= n; i++) {
let bestJ = 1, bestVal = Infinity;
const candidates = [];
for (let j = 1; j * j <= i; j++) {
candidates.push({j, sq: j*j, val: dp[i - j*j] + 1});
if (dp[i - j*j] + 1 < bestVal) { bestVal = dp[i - j*j] + 1; bestJ = j; }
}
steps.push({stage:'try', msg:`计算 dp[${i}]:尝试所有平方数`, dp:[...dp], current:i, bestJ:-1, candidates});
dp[i] = bestVal;
steps.push({stage:'fill', msg:`dp[${i}] = dp[${i-bestJ*bestJ}]+1 = ${dp[i-bestJ*bestJ]}+1 = ${bestVal}(选 ${bestJ}²=${bestJ*bestJ})`, dp:[...dp], current:i, bestJ, candidates});
}
steps.push({stage:'done', msg:`${n} 最少需要 ${dp[n]} 个完全平方数`, dp:[...dp], current:n, bestJ:-1, candidates:[]});
}
function render(step) {
const s = steps[step];
let viz = '<div style="margin-top:8px;"><b>dp 表:</b></div>';
viz += '<div style="display:flex;flex-wrap:wrap;gap:4px;margin:8px 0;">';
for (let i = 0; i <= n; i++) {
let cls = 'default';
if (i === s.current) cls = s.stage==='try'?'orange':'green';
if (s.bestJ > 0 && i === s.current - s.bestJ*s.bestJ) cls = 'blue';
const val = s.dp[i] === Infinity ? '∞' : s.dp[i];
viz += `<span class="chip-group"><span class="chip ${cls}" style="min-width:32px;font-size:13px;">${val}</span><span class="chip-index">${i}</span></span>`;
}
viz += '</div>';
if (s.candidates && s.candidates.length > 0) {
viz += '<div style="margin-top:8px;"><b>候选平方数:</b></div>';
viz += '<div style="display:flex;gap:6px;flex-wrap:wrap;margin:4px 0;">';
s.candidates.forEach(c => {
const isBest = c.j === s.bestJ;
const bg = isBest ? '#dcfce7' : '#f0f9ff';
const bd = isBest ? '2px solid #16a34a' : '1px solid #cbd5e1';
viz += `<span style="padding:4px 10px;background:${bg};border:${bd};border-radius:8px;font-size:13px;">${c.j}²=${c.sq} → dp[${s.current-c.sq}]+1=${c.val===Infinity?'∞':c.val}</span>`;
});
viz += '</div>';
}
$('vizArea').innerHTML = viz;
$('detailContent').innerHTML = '<div class="calc-block">' + s.msg + '</div>';
if (s.current > 0 && s.dp[s.current] !== Infinity) {
$('detailContent').innerHTML += `<div class="current-answer">dp[${s.current}] = <b>${s.dp[s.current]}</b></div>`;
}
if (s.stage === 'done') {
$('resultContent').innerHTML = `<div class="final-answer">${n} 最少需要 <b>${s.dp[n]}</b> 个完全平方数</div>`;
}
$('hintText').textContent = s.msg;
const stages = ['init→初始化','try→尝试','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 = 'n=12';
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 = () => {
const m = $('inputArea').value.match(/n=(\d+)/);
if (!m) { alert('格式: n=12'); return; }
buildSteps(parseInt(m[1]));
stepCtrl.setSteps(steps.map((_,i)=>i)); render(0); $('stepInfo').textContent = '步骤 1 / ' + steps.length;
};
$('exampleSelect').onchange = () => {
const e = examples[parseInt($('exampleSelect').value)];
$('inputArea').value = `n=${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 numSquares(n):
dp = [float('inf')] * (n + 1)
dp[0] = 0
for i in range(1, n + 1):
j = 1
while j * j <= i:
dp[i] = min(dp[i], dp[i - j*j] + 1)
j += 1
return dp[n]`, {lang:'Python'});
})();
</script>
</body>
</html>