week13-leetcode #300-Longest-Increasing-Subsequence
链接:https://leetcode.com/problems/longest-increasing-subsequence/description/
Question
Given an unsorted array of integers, find the length of longest increasing subsequence.
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.
Note:
- Your algorithm should run in O(n2) complexity.
Solution
time complecity: O(n2)
class Solution {
public:
int lengthOfLIS(vector<int>& nums) {
if (nums.size() == 0) return 0;
int num_size = nums.size();
bool **is_relate = new bool*[num_size];
for (int i = 0; i < num_size; i++)
is_relate[i] = new bool[num_size];
for (int i = 0; i < num_size; i++) {
for (int j = 0; j < num_size; j++) {
if (i != j && nums[i] < nums[j])
is_relate[i][j] = true;
else
is_relate[i][j] = false;
}
}
vector<int> L(num_size, 1);
int result = -9999;
for (int j = 0; j < num_size; j++) {
int max_value = -9999;
for (int i = 0; i < j; i++) {
if (is_relate[i][j]) {
max_value = max(max_value, L[i]);
}
}
if (max_value > 0)
L[j] = 1+max_value;
result = max(result, L[j]);
}
return result;
}
};
思路:将所有数据点看成是一个图中的节点,遍历所有数据,若出现
nums(i)<nums(j)
的情况,则认为存在一条从i节点到j节点的边,则问题转化为求这个有向无环图(dag)的边值权重为1的最长路径。最长路径采用动态规划的方法进行求解。其中动态规划的状态转换方程如下:
1<=j<size,L[j]=max1<=i<j{L[i]}+1,其中节点i有指向节点j的边