# Thinking——斐波拉契数列不用递归

## 斐波拉契数列

1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233……

\$\$ F_{n}=F_{{n-1}}+F_{{n-2}}（n≧2） \$\$

## 递归方法求解

``````// n从1开始
function fib(n) {
if (n <= 2)
return 1;
return fib(n - 1) + fib(n - 2);
}``````

## 循环方法求解

``````// n从1开始
function fibFor(n) {
if (n <= 2)
return 1;
let arr = [];
//arr[0] = 0;
arr[2] = arr[1] = 1;
for (let i = 3; i <= n; i++) {
arr[i] = arr[i - 1] + arr[i - 2];
}
return arr[n];
}``````

``````// n从1开始
function fibFor2(n) {
if (n <= 2)
return 1;
let before2 = 1;
let before1 = 1;
let now = null;
for (let i = 3; i <= n; i++) {
now = before1 + before2;
before2 = before1;
before1 = now;
}
return now;
}``````

## 进一步：LCS问题

### 思路

``````package main

import "fmt"

func max(x, y int) int {
if x > y {
return x
}
return y
}

func LongestCommonSequence(a string, b string) int {
aChars := []rune(a)
bChars := []rune(b)
aLen := len(aChars)
bLen := len(bChars)
if aLen == 0 || bLen == 0 {
return 0
}
if aChars[aLen-1] == bChars[bLen-1] {
return LongestCommonSequence(string(aChars[:aLen-1]), string(bChars[:bLen-1])) + 1
} else {
return max(
LongestCommonSequence(string(aChars[:aLen-1]), b),
LongestCommonSequence(a, string(bChars[:bLen-1])))
}
}

func main() {
a := "ACDE"
b := "CBE"
fmt.Printf("Longest sub sequence length of %s and %s is %d\n", a, b,
LongestCommonSequence(a, b))
}``````

``````func LongestCommonSequenceDP(a string, b string) int {
aChars := []rune(a)
bChars := []rune(b)
aLen := len(aChars)
bLen := len(bChars)
if aLen == 0 || bLen == 0 {
return 0
}

record := make([][]int, aLen+1)
for i := 0; i <= aLen; i++ {
record[i] = make([]int, bLen+1)
record[i][0] = 0
}

for j := 0; j <= bLen; j++ {
record[0][j] = 0
}

for i := 1; i <= aLen; i++ {
for j := 1; j <= bLen; j++ {
if aChars[i-1] == bChars[j-1] {
record[i][j] = record[i-1][j-1] + 1
} else {
record[i][j] = max(record[i][j-1], record[i-1][j])
}
}
}

return record[aLen][bLen]
}``````

6.7k 声望
407 粉丝
0 条评论