题意理解
给定一个字符串,问最长的递增子序列有多长,(可以不连续)。
问题分析
用动规,状态量,状态转移方程
状态量 DP[i] 前i个字符(带第i个字符)的递增子序列最长长度
状态转移方程
DP[i] = max( DP[j] ) + 1, 0 <= j <= i;
这次的规律不是i个状态和i-1个状态的关系,而是i个状态和0..i-1个状态的关系。
最终的最大值也是所有最大值的最大值。
其他
方法是这样,但道理有点麻烦,没弄通。
This method relies on the fact that the longest increasing subsequence possible upto the i^{th}ith index in a given array is independent of the elements coming later on in the array. Thus, if we know the length of the LIS upto i^{th}ith index, we can figure out the length of the LIS possible by including the (i+1)^{th}(i+1)th element based on the elements with indices jj such that 0 \leq j \leq (i + 1)0≤j≤(i+1).
链接
int lengthOfLIS(vector<int>& nums) {
if (nums.size() == 0)
return 0;
if (nums.size() == 1)
return 1;
int dp[nums.size()];
dp[0] = 1;
for (int i = 1; i < nums.size(); i++)
{
int maxVal = 0;
for(int j = 0; j < i; j ++)
{
if (nums[j] < nums[i])
{
maxVal = max(maxVal, dp[j]);
}
}
dp[i] = maxVal + 1;
cout << i << '\t' << dp[i] << endl;
}
int maxLen = 0;
for(int i = 0; i < nums.size(); i++)
maxLen = max(maxLen, dp[i]);
return maxLen;
}