From f9abccf8892f4d7054806a97a84110846e3d047f Mon Sep 17 00:00:00 2001 From: hailincai Date: Sun, 24 Oct 2021 09:53:42 -0400 Subject: [PATCH] =?UTF-8?q?Update=200376.=E6=91=86=E5=8A=A8=E5=BA=8F?= =?UTF-8?q?=E5=88=97.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 增加dp方法 --- problems/0376.摆动序列.md | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/problems/0376.摆动序列.md b/problems/0376.摆动序列.md index 5587a8c7..e58a26ff 100644 --- a/problems/0376.摆动序列.md +++ b/problems/0376.摆动序列.md @@ -199,6 +199,36 @@ class Solution { } ``` +```java +// DP +class Solution { + public int wiggleMaxLength(int[] nums) { + // 0 i 作为波峰的最大长度 + // 1 i 作为波谷的最大长度 + int dp[][] = new int[nums.length][2]; + + dp[0][0] = dp[0][1] = 1; + for (int i = 1; i < nums.length; i++){ + //i 自己可以成为波峰或者波谷 + dp[i][0] = dp[i][1] = 1; + + for (int j = 0; j < i; j++){ + if (nums[j] > nums[i]){ + // i 是波谷 + dp[i][1] = Math.max(dp[i][1], dp[j][0] + 1); + } + if (nums[j] < nums[i]){ + // i 是波峰 + dp[i][0] = Math.max(dp[i][0], dp[j][1] + 1); + } + } + } + + return Math.max(dp[nums.length - 1][0], dp[nums.length - 1][1]); + } +} +``` + Python: ```python3 class Solution: