LeetCode 300. 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.
大致题意
在数组里面找到最长递增子序列
题解
问题类型:dp,二分
设 dp[i] 表示选择第 i 个元素的递增子序列中最长的长度
动态转移方程:dp[i] = max(dp[j] + 1, dp[i])
题解如下
class Solution {
public:
int lengthOfLIS(vector<int>& nums) {
if (!nums.size()) {
return 0;
}
vector<int> dp(nums.size(), 1);
int res = 1;
for (int i = 1; i < nums.size(); i++) {
for (int j = 0; j < i; j++) {
if (nums[j] < nums[i]) {
dp[i] = max(dp[j] + 1, dp[i]);
}
}
res = max(dp[i], res);
}
return res;
}
};
评论
登录后参与技术讨论,分享你的经验与见解。
登录 / 注册暂无评论