【leetcode刷题】T165-最长上升子序列
- 2019 年 10 月 4 日
- 筆記
木又连续日更第1天(1/100)
木又的第165篇leetcode解题报告
动态规划
类型第10篇解题报告
leetcode第300题:最长上升子序列
https://leetcode-cn.com/problems/longest-increasing-subsequence/
【题目】
给定一个无序的整数数组,找到其中最长上升子序列的长度。
示例: 输入: [10,9,2,5,3,7,101,18] 输出: 4 解释: 最长的上升子序列是 [2,3,7,101],它的长度是 4。
说明:
可能会有多种最长上升子序列的组合,你只需要输出对应的长度即可。 你算法的时间复杂度应该为 O(n2) 。
【思路】
这是一道很正常的动态规划题目:dp[i] = max(dp[j] + 1),这里的第j个元素需要满足条件nums[j] < nums[i]
【代码】
python版本
class Solution(object): def lengthOfLIS(self, nums): """ :type nums: List[int] :rtype: int """ if len(nums) < 2: return len(nums) dp = [1] * len(nums) for i in range(1, len(nums)): for j in range(i-1, -1, -1): if nums[i] > nums[j]: dp[i] = max(dp[i], dp[j] + 1) return max(dp)
C++版本
class Solution { public: int lengthOfLIS(vector<int>& nums) { if(nums.size() < 2) return nums.size(); vector<int> dp(nums.size(), 1); int res = 1; for(int i=1; i<nums.size(); i++){ for(int j=i-1; j >= 0; j--){ if(nums[i] > nums[j]) dp[i] = max(dp[i], dp[j] + 1); } res = max(res, dp[i]); } return res; } };