mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-10 04:06:51 +08:00
Merge pull request #1263 from dxx99/master
0300.最长上升子序列-0674.最长连续递增序列-添加go版本解法
This commit is contained in:
@ -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
|
||||||
```javascript
|
```javascript
|
||||||
const lengthOfLIS = (nums) => {
|
const lengthOfLIS = (nums) => {
|
||||||
|
@ -236,6 +236,45 @@ class Solution:
|
|||||||
```
|
```
|
||||||
|
|
||||||
Go:
|
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:
|
Javascript:
|
||||||
|
|
||||||
|
Reference in New Issue
Block a user