求数组的最长递增子序列

179 阅读1分钟

一 、 什么是最长递增子序列

最长递增子序列是值从number数组中,随意取出一些数字的组合,能够满足这些数字的组合按照下标出现的顺序值是递增的。

比如 :arr = [3, 4, 1, 2, 3, 7, 5, 8, 10]; 的最长递增子序列就是 [ 1, 2, 3, 5, 8, 10 ]

二、 思路

arr = [3, 4, 1, 2, 3, 7, 5, 8, 10]; 为例:

我们首先维护一个二维数组,temp,然后从头遍历 arr, 更新temp

temp: 是一个二维数组,以下每一行对应temp 的每一行

3  // 遍历33 , 4 // 遍历4// 遍历1, 此时的temp是:
1
34// 遍历2
1
12
123 // 遍历3
1237//遍历7// 遍历5
1
12
123 
1235
12358 // 8
1, 2, 3, 5, 8,10 //10
​
最佳的结果就额是 123,,5810

三、 上代码

const arr = [3, 4, 1, 2, 3, 7, 5, 8, 10];
​
function getLongestIncrease(arr) {
    // 初始化数组
    const temp = [[arr[0]]];
    for (let i = 1; i < arr.length; i++) {
        const n = arr[i];
        // 根据 n 和当前的temp ,更新temp
        for (let j = temp.length - 1; j >= 0; j--) {
            const line = temp[j];
            const tail = line[line.length - 1];
            if (n > tail) {
                temp[j + 1] = [...line, n];
                break;
            } else if (n < tail && j === 0) {
                temp[j] = [n];
                break;
            }
        }
    }
    // 返回temp的最后一项
    return temp[temp.length - 1];
}
​
console.log(getLongestIncrease(arr));

temp的含义: temp数组的第 i 项代表考虑当前已经遍历完成的项中,最长递增子序列的长度为 i 的最优解。把数组遍历完,temp 的长度就是最长递增子序列的长度,temp的最后一项就是最长递增子序列。