博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
【Lintcode】076.Longest Increasing Subsequence
阅读量:5136 次
发布时间:2019-06-13

本文共 2353 字,大约阅读时间需要 7 分钟。

题目:

Given a sequence of integers, find the longest increasing subsequence (LIS).

You code should return the length of the LIS.

Clarification

What's the definition of longest increasing subsequence?

  • The longest increasing subsequence problem is to find a subsequence of a given sequence in which the subsequence's elements are in sorted order, lowest to highest, and in which the subsequence is as long as possible. This subsequence is not necessarily contiguous, or unique.

Example

For [5, 4, 1, 2, 3], the LIS is [1, 2, 3], return 3

For [4, 2, 4, 5, 3, 7], the LIS is [2, 4, 5, 7], return 4

题解:

  For dp[i], dp[i] is max(dp[j]+1, dp[i]), for all j < i and nums[j] < nums[i].

Solution 1 ()

class Solution {public:    int longestIncreasingSubsequence(vector
nums) { if (nums.empty()) { return 0; } vector
dp(nums.size(), 1); int res = 1; for (int i = 1; i < nums.size(); ++i) { for (int j = 0; j < i; ++j) { if (nums[j] < nums[i]) { dp[i] = max(dp[i], dp[j] + 1); } } res = max(dp[i], res); } return res; }};

Solution 2 ()

class Solution {public:    /**     * @param nums: The integer array     * @return: The length of LIS (longest increasing subsequence)     */    int longestIncreasingSubsequence(vector
nums) { vector
res; for(int i=0; i

Solution 3 ()

class Solution {public:    int longestIncreasingSubsequence(vector
nums) { if (nums.empty()) { return 0; } vector
tmp; tmp.push_back(nums[0]); for (auto num : nums) { if (num < tmp[0]) { tmp[0] = num; } else if (num > tmp.back()) { tmp.push_back(num); } else { int begin = 0, end = tmp.size(); while (begin < end) { int mid = begin + (end - begin) / 2; if (tmp[mid] < num) { begin = mid + 1; } else { end = mid; } } tmp[end] = num; } } return tmp.size(); }};

 

转载于:https://www.cnblogs.com/Atanisi/p/6883116.html

你可能感兴趣的文章
iOS按钮长按
查看>>
Shell流程控制
查看>>
CSS属性值currentColor
查看>>
[Leetcode|SQL] Combine Two Tables
查看>>
《DSP using MATLAB》Problem 7.37
查看>>
ROS lesson 1
查看>>
js笔记
查看>>
c风格字符串函数
查看>>
python基础学习第二天
查看>>
java可重入锁reentrantlock
查看>>
浅谈卷积神经网络及matlab实现
查看>>
struts2学习(9)struts标签2(界面标签、其他标签)
查看>>
Android 导入jar包 so模块--导入放置的目录
查看>>
解决ajax请求cors跨域问题
查看>>
Android Studio
查看>>
zz 圣诞丨太阁所有的免费算法视频资料整理
查看>>
【大数模板】C++大数类 大数模板
查看>>
【123】
查看>>
《收获,不止Oracle》pdf
查看>>
用户权限设置
查看>>