Skip to content

Commit 1e368e7

Browse files
committed
动态规划: 最长上升子序列
Change-Id: Ib3dec4f2ba2df80f52fd6291e26ba502afc11c5d
1 parent aef344e commit 1e368e7

File tree

2 files changed

+71
-1
lines changed

2 files changed

+71
-1
lines changed
+70
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
/*
2+
* @lc app=leetcode.cn id=300 lang=golang
3+
*
4+
* [300] 最长上升子序列
5+
*
6+
* https://leetcode-cn.com/problems/longest-increasing-subsequence/description/
7+
*
8+
* algorithms
9+
* Medium (43.34%)
10+
* Likes: 360
11+
* Dislikes: 0
12+
* Total Accepted: 38.6K
13+
* Total Submissions: 88.7K
14+
* Testcase Example: '[10,9,2,5,3,7,101,18]'
15+
*
16+
* 给定一个无序的整数数组,找到其中最长上升子序列的长度。
17+
*
18+
* 示例:
19+
*
20+
* 输入: [10,9,2,5,3,7,101,18]
21+
* 输出: 4
22+
* 解释: 最长的上升子序列是 [2,3,7,101],它的长度是 4。
23+
*
24+
* 说明:
25+
*
26+
*
27+
* 可能会有多种最长上升子序列的组合,你只需要输出对应的长度即可。
28+
* 你算法的时间复杂度应该为 O(n^2) 。
29+
*
30+
*
31+
* 进阶: 你能将算法的时间复杂度降低到 O(n log n) 吗?
32+
*
33+
*/
34+
35+
/*
36+
* 求极值第一反应是动态规划,状态转移方程是dp[i]=max(dp[i], nums[i]>nums[j] ? dp[j]+1 : dp[j])
37+
* 其中,dp[i]表示0~i之间最长上升子序列长,0<j<i;遍历0-i,如果小于nums[i]则与dp[i]对比一下,看看能否更新
38+
* PS: 如果要求连续的最长则可以简化成只记录一个max变量,然后找各个子串的最长值
39+
*/
40+
41+
// package leetcode
42+
43+
// @lc code=start
44+
func lengthOfLIS(nums []int) int {
45+
n := len(nums)
46+
if n <= 1 {
47+
return n
48+
}
49+
res := 1
50+
dp := make([]int, n)
51+
for i := 0; i < n; i++ {
52+
dp[i] = 1 // 每个元素不与别的元素比较最短都是1个长度
53+
for j := 0; j < i; j++ {
54+
if nums[j] < nums[i] {
55+
dp[i] = max(dp[i], dp[j]+1)
56+
}
57+
}
58+
res = max(res, dp[i])
59+
}
60+
return res
61+
}
62+
63+
func max(a, b int) int {
64+
if a > b {
65+
return a
66+
}
67+
return b
68+
}
69+
70+
// @lc code=end

go/leetcode/88.合并两个有序数组.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@
3333
*/
3434

3535
// 先规划空间然后从后往前元素进去
36-
package leetcode
36+
// package leetcode
3737

3838
// @lc code=start
3939
func merge(nums1 []int, m int, nums2 []int, n int) {

0 commit comments

Comments
 (0)