递归思想
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>递归思想</title>
</head>
<body>
</body>
</html>
非递归解决问题
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>递归思想 - 非递归解决问题</title>
</head>
<body></body>
<script>
const cities = [
{
name: "广东",
children: [
{
name: "广州",
children: [
{
name: "越秀",
},
{
name: "天河",
children: [
{
name: "吉山",
},
],
},
],
},
{
name: "深圳",
children: [
{
name: "南山",
},
],
},
],
},
];
cities.forEach((item) => {
document.body.innerHTML += `<div>${item.name}</div>`;
if (item.children) {
item.children.forEach((item) => {
document.body.innerHTML += `<div>${item.name}</div>`;
if (item.children) {
item.children.forEach((item) => {
document.body.innerHTML += `<div>${item.name}</div>`;
if (item.children) {
item.children.forEach((item) => {
document.body.innerHTML += `<div>${item.name}</div>`;
if (item.children) {
item.children.forEach((item) => {
document.body.innerHTML += `<div>${item.name}</div>`;
});
}
});
}
});
}
});
}
});
</script>
</html>
递归思想 - 递归解决 - 实现遍历
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>递归思想 - 实现遍历</title>
</head>
<body></body>
<script>
const cities = [
{
name: "广东",
children: [
{
name: "广州",
children: [
{
name: "越秀",
},
{
name: "天河",
children: [
{
name: "吉山",
children: [
{
name: "张三",
},
],
},
],
},
],
},
{
name: "深圳",
children: [
{
name: "南山",
},
],
},
],
},
];
function setHtml(data) {
data.forEach((item) => {
document.body.innerHTML += `<div>${item.name}</div>`;
if (item.children) setHtml(item.children);
});
}
setHtml(cities);
</script>
</html>
递归思想 - 显示出口
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>递归思想 - 显示出口</title>
</head>
<body></body>
<script>
function fbnq(n) {
if (n <= 2) return 1;
return fbnq(n - 1) + fbnq(n - 2);
}
console.time("随便");
console.log(fbnq(50));
console.timeEnd("随便");
</script>
</html>
|