栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

最长上升子序列LIS

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

最长上升子序列LIS

问题描述:数组nums中求最长上升的子序列,序列中元素不要求连续

思路参考添加链接描述

解法一
动态规划。dp[i] 表示以i为结尾的最长上升的子序列
递推公式: dp[i] = { max(dp[i], dp[j] + 1) ; 0 <= j < i && nums[i] > nums[j] }

代码实现

 private static int longestLengthOfSubsquence(int[] a) {
        int max = 1;
        int[] curentLongest = new int[a.length];
        curentLongest[0] = 1;
        for (int i = 1; i < a.length; i++) {
            curentLongest[i] = 1;
            for (int j = 0; j < i; j++) {
                if (a[i] > a[j]) {
                    curentLongest[i] = Math.max(curentLongest[i], curentLongest[j] + 1);
                }
            }
            max = Math.max(max, curentLongest[i]);
        }
        return max;
    }

解法2: 贪心算法,维护一个单调递增的栈,当前元素比栈顶元素大直接插入,当前元素比栈顶元素小,则从栈顶开始向下,将栈中最后一个大于当前元素的元素替换为当前元素

class Solution { // 8 ms, faster than 91.61%
public:
    int lengthOfLIS(vector& nums) {
        vector sub;
        for (int x : nums) {
            if (sub.empty() || sub[sub.size() - 1] < x) {
                sub.push_back(x);
            } else {
                auto it = lower_bound(sub.begin(), sub.end(), x); // Find the index of the smallest number >= x
                *it = x; // Replace that number with x
            }
        }
        return sub.size();
    }
};
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1040023.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号