LeetCode "Wiggle Subsequence" !
2016-07-24 07:31
369 查看
Another interesting DP. Lesson learnt: how you define state is crucial..
1. if DP[i] is defined as, longest wiggle(up\down) subseq AT number i, you will have O(n^2) solution
2. if DP[i] is defined as, longest wiggle(up\down) subseq SO FAR UNTIL number i, you will have O(n) solution
3. And, there's always smarter solution - GREEDY!
https://discuss.leetcode.com/topic/52074/concise-10-lines-code-0ms-acepted
1. if DP[i] is defined as, longest wiggle(up\down) subseq AT number i, you will have O(n^2) solution
class Solution { struct Rec { Rec(): mlen_dw(0), mlen_up(0){} Rec(int ldw, int lup): mlen_dw(ldw), mlen_up(lup){} int mlen_dw; int mlen_up; }; public: int wiggleMaxLength(vector<int>& nums) { int n = nums.size(); if(n < 2) return n; vector<Rec> dp(n); dp[0].mlen_up = dp[0].mlen_dw = 1; int ret = 1; for(int i = 1; i < n; i ++) { int cv = nums[i]; for(int j = i - 1; j >= max(0, ret - 2); j --) { if(cv > nums[j]) { dp[i].mlen_up = max(dp[i].mlen_up, dp[j].mlen_dw + 1); } else if(cv < nums[j]) { dp[i].mlen_dw = max(dp[i].mlen_dw, dp[j].mlen_up + 1); } ret = max(ret, max(dp[i].mlen_dw, dp[i].mlen_up)); } } return ret; } };
2. if DP[i] is defined as, longest wiggle(up\down) subseq SO FAR UNTIL number i, you will have O(n) solution
class Solution { struct Rec { Rec(): mlen_dw(0), mlen_up(0){} Rec(int ldw, int lup): mlen_dw(ldw), mlen_up(lup){} int mlen_dw; int mlen_up; }; public: int wiggleMaxLength(vector<int>& nums) { int n = nums.size(); if(n < 2) return n; vector<Rec> dp(n); dp[0].mlen_up = dp[0].mlen_dw = 1; int ret = 1; for(int i = 1; i < n; i ++) { int cv = nums[i]; dp[i] = dp[i - 1]; if(cv > nums[i - 1]) { dp[i].mlen_up = max(dp[i].mlen_up, dp[i - 1].mlen_dw + 1); } else if(cv < nums[i - 1]) { dp[i].mlen_dw = max(dp[i].mlen_dw, dp[i - 1].mlen_up + 1); } ret = max(ret, max(dp[i].mlen_dw, dp[i].mlen_up)); } return ret; } };
3. And, there's always smarter solution - GREEDY!
https://discuss.leetcode.com/topic/52074/concise-10-lines-code-0ms-acepted
相关文章推荐
- [JAVA]String StringBuffer StringBuilder
- 安卓6.0版本更新以后无法利用BluetoothDevice.ACTION_FOUND查找周围设备
- UITableView 到达顶部或底部的判断
- String、StringBuffer、StringBuilder
- JS中的==运算: [''] == false ―>true
- 为Mac OS X 中的MAMP安装 libmosquitto PHP扩展
- UITextFiled、UITextView按字节限制输入长度
- UISearchBar
- UEditor学习笔记(一)
- 【Leetcode】Guess Number Higher or Lower II
- JBuilder中切换编辑文件标签的键盘快捷键
- junit4定义测试集TestSuite Declaration
- JBuilder中光标错位的解决办法
- QQLite 插件开发 之 html解析 CsQuery(C#)
- 使用ProcessBuilder执行本地命令
- EasyUI_Datagrid上下键编辑行,锁定编辑单元格所在的列(二)
- 关于布局TabBar方法总结
- EasyUI_Datagrid编辑-键盘上下键选择行(一)
- hdu5749Colmerauer
- 55.View the Exhibit to examine the output produced by the following query at three different times s