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) => { 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: