leetcode@ [300] Longest Increasing Subsequence (记忆化搜索)

时间:2021-11-15 06:33:39

https://leetcode.com/problems/longest-increasing-subsequence/

Given an unsorted array of integers, find the length of longest increasing subsequence.

For example,
Given [10, 9, 2, 5, 3, 7, 101, 18],
The longest increasing subsequence is [2, 3, 7, 101], therefore the length is 4. Note that there may be more than one LIS combination, it is only necessary for you to return the length.

Your algorithm should run in O(n2) complexity.

Follow up: Could you improve it to O(n log n) time complexity?

class Solution {
public:
int dfs(vector<int>& nums, vector<int> &dp, int v) {
if(dp[v]) return dp[v];
if(v == ) return ; int res = -;
for(int nv=v-;nv>=;--nv) {
if(nums[nv] >= nums[v]) continue;
res = max(res, dfs(nums, dp, nv));
}
dp[v] = res + ;
return dp[v];
}
int lengthOfLIS(vector<int>& nums) {
if(nums.size() == || nums.size() == ) return nums.size(); vector<int> dp(nums.size(), ); int res = -;
for(int i=nums.size()-;i>=;--i) {
dp[i] = dfs(nums, dp, i);
res = max(res, dp[i] + );
} return res;
}
};