Files
illustrated-algorithm/pascals-triangle/index.html
T
2026-08-24 04:35:13 +00:00

188 lines
7.4 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>082. 杨辉三角 – 图解</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>🟢 082. 杨辉三角 <span class="badge easy">简单</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: 5, label: '示例1: numRows=5'},
{input: 1, label: '示例2: numRows=1'},
{input: 7, label: '示例3: numRows=7'},
];
let steps, stepCtrl, numRows;
function buildSteps(n) {
numRows = n; steps = [];
const triangle = [];
steps.push({stage:'init', msg:'开始生成杨辉三角,每行首尾为1,中间元素 = 上方两数之和', triangle:[], row:-1, col:-1});
for (let i = 0; i < numRows; i++) {
const row = new Array(i + 1).fill(1);
steps.push({stage:'newRow', msg:`第 ${i} 行共 ${i+1} 个元素,首尾均为 1`, triangle:JSON.parse(JSON.stringify(triangle)), row:i, col:-1});
for (let j = 1; j < i; j++) {
row[j] = triangle[i-1][j-1] + triangle[i-1][j];
steps.push({stage:'calc', msg:`triangle[${i}][${j}] = triangle[${i-1}][${j-1}] + triangle[${i-1}][${j}] = ${triangle[i-1][j-1]} + ${triangle[i-1][j]} = ${row[j]}`, triangle:JSON.parse(JSON.stringify(triangle)), row:i, col:j});
}
triangle.push([...row]);
steps.push({stage:'fillRow', msg:`第 ${i} 行填充完毕:[${row.join(', ')}]`, triangle:JSON.parse(JSON.stringify(triangle)), row:i, col:i});
}
steps.push({stage:'done', msg:`杨辉三角生成完毕,共 ${numRows} 行`, triangle:JSON.parse(JSON.stringify(triangle)), row:-1, col:-1});
}
function render(step) {
const s = steps[step];
let viz = '<div style="display:flex;flex-direction:column;align-items:center;gap:4px;padding:12px 0;">';
const maxRow = s.triangle.length;
for (let i = 0; i < maxRow; i++) {
const gap = Math.max(2, (maxRow - i) * 6);
viz += `<div style="display:flex;gap:${gap}px;justify-content:center;">`;
for (let j = 0; j <= i; j++) {
const val = s.triangle[i][j];
let cls = 'default';
if (i === s.row && s.stage !== 'done') {
cls = j === s.col ? 'orange' : 'green';
}
if (s.stage === 'calc' && i === s.row - 1 && (j === s.col - 1 || j === s.col)) {
cls = 'blue';
}
viz += `<span class="chip ${cls}" style="min-width:32px;height:28px;font-size:13px;">${val}</span>`;
}
viz += '</div>';
}
if (s.stage === 'newRow' || s.stage === 'calc') {
viz += `<div style="display:flex;gap:2px;justify-content:center;margin-top:2px;">`;
for (let j = 0; j <= s.row; j++) {
viz += `<span style="min-width:32px;height:28px;border:2px dashed var(--orange);border-radius:10px;display:flex;align-items:center;justify-content:center;font-size:13px;color:var(--text-muted);">?</span>`;
}
viz += '</div>';
}
viz += '</div>';
$('vizArea').innerHTML = viz;
let detail = '<div class="calc-block">' + s.msg + '</div>';
if (s.triangle.length > 0) {
detail += '<div style="margin-top:8px;"><b>当前三角:</b></div>';
s.triangle.forEach((row, i) => {
detail += `<div style="margin:2px 0;"><code>${i}: [${row.join(', ')}]</code></div>`;
});
}
$('detailContent').innerHTML = detail;
if (s.stage === 'done') {
$('resultContent').innerHTML = `<div class="final-answer">杨辉三角 <b>${numRows}</b> 行已生成</div>`;
}
$('hintText').textContent = s.msg;
const stages = ['init→开始','newRow→新行','calc→计算','fillRow→填充','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 = 'numRows=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 = () => {
const m = $('inputArea').value.match(/numRows=(\d+)/);
if (!m) { alert('格式: numRows=5'); 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 = `numRows=${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 generate(numRows):
triangle = []
for i in range(numRows):
row = [1] * (i + 1)
for j in range(1, i):
row[j] = triangle[i-1][j-1] + triangle[i-1][j]
triangle.append(row)
return triangle`, {lang:'Python'});
})();
</script>
</body>
</html>