zoukankan      html  css  js  c++  java
  • leetcode 376Wiggle Subsequence

    用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 }
  • 相关阅读:
    zju 2886
    zju 2478
    UVA350-水题
    UVA699-落叶-二叉树
    UVA327
    UVA548
    java环境变量
    synchronized关键字
    uva297
    UVA196
  • 原文地址:https://www.cnblogs.com/hwd9654/p/10926101.html
Copyright © 2011-2022 走看看