300. Longest Increasing Subsequence
Description:
Given an unsorted array of integers, find the length of longest increasing subsequence.
Difficulty:Medium
Example:
Input: [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.
方法1:暴力, 超时
- Time complexity : O ( 2 n ) O\left ( 2^n \right ) O(2n)
- Space complexity :
O
(
n
2
)
O\left ( n^2 \right )
O(n2)
思路:
如果当前元素比前面元素prev大,有两种情况,用或者不用,用就+1
反之,只有一种情况,不用
class Solution {
public:
int lengthOfLIS(vector<int>& nums) {
return helper(nums, INT_MIN, 0);
}
int helper(vector<int>& nums, int prev, int pos){
if(pos == nums.size()) return 0;
int use = 0;
if(nums[pos] > prev)
use = helper(nums, nums[pos], pos+1) + 1;
int no_use = helper(nums, prev, pos+1);
return max(use, no_use);
}
};
方法2:动态规划
- Time complexity : O ( n 2 ) O\left ( n^2 \right ) O(n2)
- Space complexity :
O
(
n
)
O\left ( n \right )
O(n)
思路:
dp[i] = max(dp[j])+1 if nums[i] > nums[j] ,( j = 0->i-1)
class Solution {
public:
int lengthOfLIS(vector<int>& nums) {
if(nums.size() == 0) return 0;
int res = 1;
vector<int> dp(nums.size()+1);
dp[0] = 1;
for(int i = 1; i < nums.size(); i++){
int max_val = 0;
for(int j = 0; j < i; j++){
if(nums[j] < nums[i]) max_val = max(dp[j], max_val);
}
dp[i] = max_val + 1;
res = max(dp[i], res);
}
return res;
}
};