300. Longest Increasing Subsequence(DP经典问题)
来源:互联网 发布:相宜本草淘宝有假货吗 编辑:程序博客网 时间:2024/06/04 20:47
Given an unsorted array of integers, find the length of longest increasing subsequence.
For example,
Given [10, 9, 2, 5, 3, 7, 101, 18]
,
The longest increasing subsequence is [2, 3, 7, 101]
, therefore the length is 4
. Note that there may be more than one LIS combination, it is only necessary for you to return the length.
Your algorithm should run in O(n2) complexity.
Follow up: Could you improve it to O(n log n) time complexity?
Credits:
Special thanks to @pbrother for adding this problem and creating all test cases.
这个状态转移方程还是容易想的,定义dp[i]是在第i个位置能取得的最大长度,那么dp[i]=max(dp[i],dp[j]+1),其中j∈[0,i),加1的前提是dp[j]<dp[i],但是!一定不要粗心,最后的答案应该是dp数组中最大的那个,所以如果不怕浪费时间,可以最后sort一下再return dp[n-1],否则的话可以弄一个int型的变量res每次和得到的dp[i]比一比,总是取最大的res,最后return res
AC代码:
class Solution {public: int lengthOfLIS(vector<int>& nums) { int n=nums.size(); vector<int>dp(n,0); if(n==0)return 0; for(int i=0;i<n;i++){ dp[i]=1; for(int j=0;j<i;j++){ if(nums[j]<nums[i]) dp[i]=max(dp[i],dp[j]+1); } } sort(dp.begin(),dp.end()); return dp[n-1]; }};
LeetCode的测试样例只有24个,如果直接return dp[n-1]只有两个样例通不过,哈哈哈哈。。。。(虽然这好像也不是什么好笑的事。。。)
进一步地,解决这个问题的算法可以被优化到O(nlogn),详细的介绍可以看这里:http:www.geeksforgeeks.org/longest-monotonically-increasing-subsequence-size-n-log-n/
- 300. Longest Increasing Subsequence(DP经典问题)
- 300. Longest Increasing Subsequence/DP
- 【DP】 Longest Increasing Subsequence
- [DP]Longest Increasing Subsequence
- LeetCode Longest Increasing Subsequence DP
- 300. Longest Increasing Subsequence
- 300. Longest Increasing Subsequence
- 300. Longest Increasing Subsequence
- 300. Longest Increasing Subsequence
- 300. Longest Increasing Subsequence
- 300. Longest Increasing Subsequence
- 300. Longest Increasing Subsequence
- 300. Longest Increasing Subsequence
- 300. Longest Increasing Subsequence
- 300. Longest Increasing Subsequence
- 300. Longest Increasing Subsequence
- 300. Longest Increasing Subsequence
- 300. Longest Increasing Subsequence
- 全面解析Bootstrap表单使用方法(表单按钮)
- 适配器模式(2)
- Google算法题:三数求和
- 手势监听上下左右
- Ubuntu16.04lTS安装qq文件时在处理时有错误发生:xxxi386问题
- 300. Longest Increasing Subsequence(DP经典问题)
- 利用豆瓣短评数据生成词云
- eclipse 设置默认编码为Utf-8
- Oracle11g安装(Linux)
- 【链家笔试题】问卷调查
- [NOIP2016真题]组合数问题
- 使用MySql replace into(insert into 的增强版)时你不得不注意的坑
- java新手如何简单的理解java数组中冒泡排序法是怎么实现排序的
- 安卓Activity详解(生命周期-以各种方式启动Activity-状态保存-完全退出)