問題描述
連結: https://leetcode.com/problems/longest-increasing-subsequence/description/
Given an integer array
nums
, return the length of the longest strictly increasing subsequence
解釋:給定一個陣列nums,返回長的嚴格遞增子序列。
案例:
Input: nums = [10,9,2,5,3,7,101,18]
Output: 4
Explanation: The longest increasing subsequence is [2,3,7,101], therefore the length is 4.
基本思想
經典題型。
構造陣列dp,大小等於nums的大小。
- \(dp[i]\): 以 \(nums[i]\)為結尾的最長嚴格遞增子序列
- 則 \(dp[i]\) 依賴於 \(nums[0~ i-1]\) 比 \(nums[i]\)小的數,對應的下標index相應的\(dp[index]\)
- 其更新公式如下:
- \(dp[i]\) = \(max(dp[j]+1)\) \(\quad\) 其中\(0<j<(i-1) \quad and \quad nums[j]<nums[i]\)$
時間複雜度 \(o(n^2)\)
程式碼
C++
int lengthOfLIS(vector<int>& nums) {
int n = nums.size();
if(n<=1) return n;
vector<int> dp(n,1); // dp[i]表示以nums[i]為結尾的最長遞增子序列
int res = 0;
for(int i=1;i<n;++i) {
int t = 1;
for(int j=0;j<i;++j) {
if (nums[j]<nums[i]) {
t = max(t, dp[j]+1);
}
}
dp[i] = t;
res = max(res, dp[i]);
}
return res;
}
python
def lengthOfLIS(self, nums: List[int]) -> int:
n = len(nums)
if n<=1: return n
dp=[1] * n
res = 1
for i in range(1,n):
t = 1
for j in range(0,i):
if nums[i] > nums[j]:
t = max(t, dp[j]+1)
dp[i] = t
res = max(res, dp[i])
return res