Files
illustrated-algorithm/longest-increasing-subsequence/index.html
T
2026-08-24 04:35:13 +00:00

180 lines
7.1 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>087. 最长递增子序列 – 图解</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>🟡 087. 最长递增子序列 <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: [10,9,2,5,3,7,101,18], label: '示例1: [10,9,2,5,3,7,101,18]'},
{input: [0,1,0,3,2,3], label: '示例2: [0,1,0,3,2,3]'},
{input: [7,7,7,7,7,7,7], label: '示例3: [7,7,7,7,7,7,7]'},
];
let nums, steps, stepCtrl;
function buildSteps(arr) {
nums = [...arr]; steps = [];
const n = nums.length;
if (n === 0) { steps.push({stage:'done', msg:'数组为空', dp:[], best:0, prev:[]}); return; }
const dp = new Array(n).fill(1);
const prev = new Array(n).fill(-1);
steps.push({stage:'init', msg:'每个元素自身构成长度为1的递增子序列', dp:[...dp], current:-1, bestIdx:0, prev:[...prev]});
let bestIdx = 0;
for (let i = 1; i < n; i++) {
steps.push({stage:'check', msg:`检查 nums[${i}]=${nums[i]},寻找 j<i 使得 nums[j]<nums[${i}]`, dp:[...dp], current:i, bestIdx, j:-1, prev:[...prev]});
for (let j = 0; j < i; j++) {
if (nums[j] < nums[i] && dp[j] + 1 > dp[i]) {
dp[i] = dp[j] + 1;
prev[i] = j;
steps.push({stage:'update', msg:`nums[${j}]=${nums[j]} < ${nums[i]},dp[${i}] = dp[${j}]+1 = ${dp[i]}`, dp:[...dp], current:i, bestIdx, j, prev:[...prev]});
}
}
if (dp[i] > dp[bestIdx]) bestIdx = i;
steps.push({stage:'doneI', msg:`dp[${i}]=${dp[i]},最长子序列长度 = ${dp[bestIdx]}`, dp:[...dp], current:i, bestIdx, prev:[...prev]});
}
steps.push({stage:'done', msg:`最长递增子序列长度 = ${dp[bestIdx]}`, dp:[...dp], current:bestIdx, bestIdx, prev:[...prev]});
}
function render(step) {
const s = steps[step];
const hl = {};
if (s.current >= 0 && s.stage !== 'done') hl[s.current] = 'orange';
if (s.j >= 0) hl[s.j] = 'blue';
if (s.stage === 'done') {
let idx = s.bestIdx;
while (idx >= 0) { hl[idx] = 'green'; idx = s.prev[idx]; }
}
let viz = renderArray(nums, {highlights: hl});
viz += '<div style="margin-top:8px;"><b>dp 值(以每个元素结尾的 LIS 长度):</b></div>';
const dpHl = {};
if (s.current >= 0 && s.stage !== 'done') dpHl[s.current] = 'orange';
if (s.bestIdx >= 0 && s.stage === 'done') dpHl[s.bestIdx] = 'green';
viz += renderArray(s.dp, {highlights: dpHl});
if (s.stage === 'done') {
const lis = [];
let idx = s.bestIdx;
while (idx >= 0) { lis.unshift(nums[idx]); idx = s.prev[idx]; }
viz += `<div style="margin-top:8px;color:var(--green);"><b>LIS: [${lis.join(', ')}]</b></div>`;
}
$('vizArea').innerHTML = viz;
$('detailContent').innerHTML = '<div class="calc-block">' + s.msg + '</div>';
if (s.bestIdx >= 0) {
$('detailContent').innerHTML += `<div class="current-answer">当前 LIS 长度:<b>${s.dp[s.bestIdx]||1}</b></div>`;
}
if (s.stage === 'done') {
$('resultContent').innerHTML = `<div class="final-answer">最长递增子序列长度 = <b>${s.dp[s.bestIdx]}</b></div>`;
}
$('hintText').textContent = s.msg;
const stages = ['init→初始化','check→检查','update→更新','doneI→完成I','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 = '[10,9,2,5,3,7,101,18]';
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 lengthOfLIS(nums):
n = len(nums)
dp = [1] * n
for i in range(1, n):
for j in range(i):
if nums[j] < nums[i]:
dp[i] = max(dp[i], dp[j] + 1)
return max(dp)`, {lang:'Python'});
})();
</script>
</body>
</html>