Lintcode76。最長の昇順部分列
タイトルの説明:整数シーケンスを指定して、最長昇順サブシーケンス(LIS)を見つけ、LISの長さを返します。
説明最長の昇順サブシーケンス
の定義
:最長の昇順サブシーケンスの問題は、特定の無秩序なシーケンスで可能な限り低いものから高いものへと配置されたサブシーケンスを見つけることです。このサブシーケンスは必ずしも連続的または一意である必要はありません。
https://en.wikipedia.org/wiki/Longest_increasing_subsequence
この質問はソリティア動的計画法に属します。厳密に言えば、これは1次元座標動的計画法です。
class Solution {
public:
/**
* @param nums: An integer array
* @return: The length of LIS (longest increasing subsequence)
*/
int longestIncreasingSubsequence(vector<int> &nums) {
if (0 == nums.size()) {
return 0;
}
//1. 初始化
vector<int> f(nums.size(), 1);//任何一个位置都可能是LIS的起点
//2. 状态转移
for (int i = 1; i < nums.size(); ++i) {
for (int j = 0; j < i; ++j) {
if (nums[j] < nums[i]) {
f[i] = max(f[i], f[j] + 1);
}
}
}
//3. 答案
auto maxLen = max_element(f.begin(), f.end());
return *maxLen;
}
};