Longest Increasing Subsequence
2016-06-16 20:57
477 查看
题目描述:
Given an unsorted array of integers, find the length of longest increasing subsequence.
For example,
Given
The longest increasing subsequence is
Note that there may be more than one LIS combination, it is only necessary for you to return the length.
解题思路:
使用动态规划,dp[i]表示以第i个元素为结尾元素的最长递增序列的长度,dp[i]初始化为1。
dp[i]=max{dp[j]+1}其中j<i 且nums[i]>nums[j]
最长的递增序列的长度即为dp[i]中的最大值
AC代码如下:
class Solution {
public:
int lengthOfLIS(vector<int>& nums) {
int n = nums.size();
if (n == 0) return 0;
vector<int> dp(n, 1);
int ans = 1;
for (int i = 1; i < n; ++i){
int count = dp[i];
for (int j = 0; j < i; ++j){
if (nums[j] <= nums[i] && count < dp[j] + 1)
count = dp[j] + 1;
}
dp[i] = count;
ans = ans < dp[i] ? dp[i] : ans;
}
return ans;
}
};
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.
解题思路:
使用动态规划,dp[i]表示以第i个元素为结尾元素的最长递增序列的长度,dp[i]初始化为1。
dp[i]=max{dp[j]+1}其中j<i 且nums[i]>nums[j]
最长的递增序列的长度即为dp[i]中的最大值
AC代码如下:
class Solution {
public:
int lengthOfLIS(vector<int>& nums) {
int n = nums.size();
if (n == 0) return 0;
vector<int> dp(n, 1);
int ans = 1;
for (int i = 1; i < n; ++i){
int count = dp[i];
for (int j = 0; j < i; ++j){
if (nums[j] <= nums[i] && count < dp[j] + 1)
count = dp[j] + 1;
}
dp[i] = count;
ans = ans < dp[i] ? dp[i] : ans;
}
return ans;
}
};
相关文章推荐
- 使用C++实现JNI接口需要注意的事项
- 关于指针的一些事情
- c++ primer 第五版 笔记前言
- share_ptr的几个注意点
- Lua中调用C++函数示例
- Lua教程(一):在C++中嵌入Lua脚本
- Lua教程(二):C++和Lua相互传递数据示例
- C++联合体转换成C#结构的实现方法
- C++高级程序员成长之路
- C++编写简单的打靶游戏
- C++ 自定义控件的移植问题
- C++变位词问题分析
- C/C++数据对齐详细解析
- C++基于栈实现铁轨问题
- C++中引用的使用总结
- 使用Lua来扩展C++程序的方法
- C++中调用Lua函数实例
- Lua和C++的通信流程代码实例
- C与C++之间相互调用实例方法讲解
- 解析C++中派生的概念以及派生类成员的访问属性