码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode "Wiggle Subsequence" !

时间:2016-07-24 08:14:10      阅读:155      评论:0      收藏:0      [点我收藏+]

标签:

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

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

LeetCode "Wiggle Subsequence" !

标签:

原文地址:http://www.cnblogs.com/tonix/p/5700042.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!