Leetcode 376 Wiggle Subsequence
题目原文
A sequence of numbers is called a wiggle sequence if the differences between successive numbers strictly alternate between positive and negative. The first difference (if one exists) may be either positive or negative. A sequence with fewer than two elements is trivially a wiggle sequence.
For example, [1,7,4,9,2,5]
is a wiggle sequence because the differences (6,-3,5,-7,3) are alternately positive and negative. In contrast,
[1,4,7,2,5]
and [1,7,4,5,5]
are not wiggle sequences, the first because its first two differences are positive and the second because its last difference is zero.
Given a sequence of integers, return the length of the longest subsequence that is a wiggle sequence. A subsequence is obtained by deleting some number of elements (eventually, also zero) from the original sequence, leaving the remaining elements in their original order.
Examples:
Input: [1,7,4,9,2,5]
Output: 6
The entire sequence is a wiggle sequence.
Input: [1,17,5,10,13,15,10,5,16,8]
Output: 7
There are several subsequences that achieve this length. One is [1,17,10,13,10,16,8].
Input: [1,2,3,4,5,6,7,8,9]
Output: 2
Follow up:
Can you do it in O(n) time?
题意分析
从一串整数中找出蛇形排列的字串,求出最长的蛇形字串,对于长度为0和1的串,认为蛇形字串长度为1。本题采用暴力方法时间复杂度为O(n!),所以需要采用巧妙的解法。
解法分析
本题采用两种解法:
- 动态规划
- 贪心算法
动态规划
本题采用自底向上的动态规划方法,分别创建数组up[n],down[n]来存储遍历到字串的第i个元素时,最后一次是up和down的蛇形字串长度,示例如下:
C++代码如下:
class Solution {
public:
int wiggleMaxLength(vector<int>& nums) {
int n=nums.size();
if(n==0)
return 0;
vector<int> up(n,1);
vector<int> down(n,1);
int i;
for(i=1;i<n;i++){
if(nums[i]>nums[i-1]){
up[i]=down[i-1]+1;
down[i]=down[i-1];
}
else if(nums[i]<nums[i-1]){
down[i]=up[i-1]+1;
up[i]=up[i-1];
}
else
{
up[i]=up[i-1];
down[i]=down[i-1];
}
}
return max(up[n-1],down[n-1]);
}
};
上述算法运算时间复杂度为O(n),为了缩减空间复杂度,由于每次计算只需用到前一次的up和down,所以不需要用数组存储所有值,只需用一个变量存储。
贪心算法
本题不需要用DP,通过分析可以看到,当数一直增加或一直减少时,总是需要选取最大或最小的那个元素进入蛇形串,示意图如下:
可以看到A、B、C、D都在上升,选A之后应该选D,这样可以保证后来得到的蛇形串最长,因为它有更大概率遇到比它小的数,形成蛇形串,这也是贪心算法正确的原因。C++代码如下:
class Solution {
public:
int wiggleMaxLength(vector<int>& nums) {
int n=nums.size();
int i;
if(n==0||n==1)
return n;
int sum=1;
int test=2;//Use test to check the up and down
for(i=1;i<n;i++){
if(test==2){
if(nums[i]>nums[i-1])
test=1;
else if(nums[i]<nums[i-1])
test=0;
if(test==2)//the input is[0,0]or[1,1]
continue;
sum++;
continue;
}
if((test==1&&(nums[i]<nums[i-1]))||(test==0&&(nums[i]>nums[i-1]))){
test=1-test;
sum++;
continue;
}
}
return sum;
}
};
上述方法更简单,关键是寻找到蛇形串的特点。