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

leetcode 376Wiggle Subsequence

时间:2019-05-26 16:02:55      阅读:79      评论:0      收藏:0      [点我收藏+]

标签:sub   情况   style   序列   res   public   长度   更新   pre   

用dp解

1)up定义为nums[i-1] < nums[i]

  down nums[i-1] > nums[i]

  两个dp数组,

  up[i],记录包含nums[i]且nums[i-1] < nums[i]的最长子序列长度

  down[], 记录包含nums[i]nums[i-1] > nums[i]的最长子序列长度

 

2)更新方程

  有三种情况 nums[i-1] <or=or> nums[i]

  a) up[i] = down[i-1] + 1;

   down[i] = down[i-1]

  b) up[i] = up[i-1]

   down[i] = down[i-1]

  c) up[i] = up[i-1]

   down[i] = up[i-1] + 1;

 

 1 class Solution {
 2     public int wiggleMaxLength(int[] nums) {
 3         if(nums == null || nums.length == 0)
 4             return 0;
 5         int len = nums.length;
 6         int[] up = new int[len];
 7         int[] down = new int[len];
 8         int res = 1;
 9         
10         up[0] = 1;
11         down[0] = 1;
12         
13         for(int i=1; i<len; i++){
14             if(nums[i] > nums[i-1]){
15                 up[i] = down[i-1] + 1;
16                 down[i] = down[i-1];
17             }else if(nums[i] < nums[i-1]){
18                 up[i] = up[i-1];
19                 down[i] = up[i-1] + 1;
20             }else{
21                 up[i] = up[i-1];
22                 down[i] = down[i-1];
23             }
24             
25             res = Math.max(res, Math.max(up[i], down[i]));
26         }
27         
28         return res;
29         
30     }
31 }

 

leetcode 376Wiggle Subsequence

标签:sub   情况   style   序列   res   public   长度   更新   pre   

原文地址:https://www.cnblogs.com/hwd9654/p/10926101.html

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