Several common JS recursive algorithms
The concept of recursion
That is, the function calls itself, or calls itself in a subordinate function called by its own function.
Recursive steps
- Assuming that the recursive function has been written
- Looking for recurrence
- Convert the structure of the recurrence relationship to a recursive body
- Add critical conditions to the recursive body
Classic case 1: Sum
Find the sum of 1-100
function sum(n) {
if (n == 1) return 1
return sum(n - 1) + n
}
复制代码
Classic case 2: Fibonacci sequence
1,1,2,3,5,8,13,21,34,55,89...Find the nth item
// 递归方法
function fib(n) {
if (n === 1 || n === 2) return n - 1
return fib(n - 1) + fib(n - 2)
}
console.log(fib(10)) // 34
//非递归方法 //
function fib(n) {
let a = 0
let b = 1
let c = a + b
for (let i = 3; i < n; i++) {
a = b
b = c
c = a + b
}
return c
}
console.log(fib(10)) // 34
复制代码
Classic case 3: Climbing stairs
JS Recursion If the stairs have n steps, you can walk 1 or 2 steps each time. How many ways are there to walk through these n steps?
function climbStairs(n) {
if (n == 1) return 1
if (n == 2) return 2
return climbStairs(n - 1) + climbStairs(n - 2)
}
复制代码
Classic case 4: Deep copy
Principle: clone(o) = new Object; returns an object
function clone(o) {
var temp = {}
for (var key in o) {
if (typeof o[key] == 'object') {
temp[key] = clone(o[key])
} else {
temp[key] = o[key]
}
}
return temp
}
复制代码
Classic case 5: Recursive components
- Recursive component: The component can call itself recursively in its template, just set the name component to the component.
- However, it should be noted that a condition must be given to limit the number, otherwise an error will be thrown: max stack size exceeded
- Component recursion is used to develop some independent components with unknown hierarchical relationships. For example: cascade selector and tree control
<template>
<div v-for="(item,index) in treeArr"> {
{index}} <br/>
<tree :item="item.arr" v-if="item.flag"></tree>
</div>
</template>
<script>
export default {
// 必须定义name,组件内部才能递归调用
name: 'tree',
data(){
return {}
},
// 接收外部传入的值
props: {
item: {
type:Array,
default: ()=>[]
}
}
}
</script>