From 5fd43cfd0a5770e0cb532687766f64306b5bbfed Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=91=A3xx?= Date: Thu, 28 Apr 2022 22:20:22 +0800 Subject: [PATCH 1/2] =?UTF-8?q?0300.=E6=9C=80=E9=95=BF=E4=B8=8A=E5=8D=87?= =?UTF-8?q?=E5=AD=90=E5=BA=8F=E5=88=97-go=E5=8A=A8=E6=80=81=E8=A7=84?= =?UTF-8?q?=E5=88=92=E6=B1=82=E8=A7=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0300.最长上升子序列.md | 33 ++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/problems/0300.最长上升子序列.md b/problems/0300.最长上升子序列.md index dfdd5125..f68edb5a 100644 --- a/problems/0300.最长上升子序列.md +++ b/problems/0300.最长上升子序列.md @@ -168,6 +168,39 @@ func lengthOfLIS(nums []int ) int { } ``` +```go +// 动态规划求解 +func lengthOfLIS(nums []int) int { + // dp数组的定义 dp[i]表示取第i个元素的时候,表示子序列的长度,其中包括 nums[i] 这个元素 + dp := make([]int, len(nums)) + + // 初始化,所有的元素都应该初始化为1 + for i := range dp { + dp[i] = 1 + } + + ans := dp[0] + for i := 1; i < len(nums); i++ { + for j := 0; j < i; j++ { + if nums[i] > nums[j] { + dp[i] = max(dp[i], dp[j] + 1) + } + } + if dp[i] > ans { + ans = dp[i] + } + } + return ans +} + +func max(x, y int) int { + if x > y { + return x + } + return y +} +``` + Javascript ```javascript const lengthOfLIS = (nums) => { From 6f85c2ad3a6daf8e0098b08e61b7fdd68d78c757 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=91=A3xx?= Date: Fri, 29 Apr 2022 00:50:22 +0800 Subject: [PATCH 2/2] =?UTF-8?q?0674.=E6=9C=80=E9=95=BF=E8=BF=9E=E7=BB=AD?= =?UTF-8?q?=E9=80=92=E5=A2=9E=E5=BA=8F=E5=88=97-go=E5=8A=A8=E6=80=81?= =?UTF-8?q?=E8=A7=84=E5=88=92=E6=B1=82=E8=A7=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0674.最长连续递增序列.md | 39 +++++++++++++++++++++++ 1 file changed, 39 insertions(+) diff --git a/problems/0674.最长连续递增序列.md b/problems/0674.最长连续递增序列.md index e941d242..56e95d97 100644 --- a/problems/0674.最长连续递增序列.md +++ b/problems/0674.最长连续递增序列.md @@ -236,6 +236,45 @@ class Solution: ``` Go: +> 动态规划: +```go +func findLengthOfLCIS(nums []int) int { + if len(nums) == 0 {return 0} + res, count := 1, 1 + for i := 0; i < len(nums)-1; i++ { + if nums[i+1] > nums[i] { + count++ + }else { + count = 1 + } + if count > res { + res = count + } + } + return res +} +``` + +> 贪心算法: +```go +func findLengthOfLCIS(nums []int) int { + if len(nums) == 0 {return 0} + dp := make([]int, len(nums)) + for i := 0; i < len(dp); i++ { + dp[i] = 1 + } + res := 1 + for i := 0; i < len(nums)-1; i++ { + if nums[i+1] > nums[i] { + dp[i+1] = dp[i] + 1 + } + if dp[i+1] > res { + res = dp[i+1] + } + } + return res +} +``` Javascript: