dp[i] 表示包含当前元素, 0 - i 所能组成上升序列的最大长度
int lengthOfLIS(vector<int>& nums) {
vector<int> dp(nums.size(),1);
int res = 0;
for(int i = 0;i<nums.size();++i){
for(int j = 0;j<i;++j){
if(nums[j] >= nums[i]) continue;
dp[i] = max(dp[i],dp[j] + 1);
}
res = max(res,dp[i]);
}
return res;
}
dp 代表的 以长度i+1结尾的 最小值 (并不是 实际的序列)
例如
1 3 7 4 8
遍历到7时 -> dp中元素 [1 3 7]
4 比 7 小 -> dp中元素为[1 3 4] 因为[1 3 4] 比[1 3 7] 更容易匹配
当已经发生过替换后,又与到比结尾大的元素,直接添加,不会影响结果
dp 代表的 以长度i+1结尾的 最小值 ,它之前的是什么元素不用管了
例如
1 3 7 4 8 5
[1 3 7]
[1 3 4]
[1 3 4 8]
[1 3 4 5]
int lengthOfLIS(vector<int>& nums) {
if(nums.empty()) return 0;
vector<int> dp= {nums[0]};
for(int i = 1;i<nums.size();++i){
if(nums[i] > dp.back()){
dp.emplace_back(nums[i]);
}else {
auto it = lower_bound(dp.begin(),dp.end(),nums[i]);
*it = nums[i];
}
}
return dp.size();
}
19万+

被折叠的 条评论
为什么被折叠?



