The so-called LIS, is the Longest Increasing Subsequence problem
Note that the sequences are necessarily contiguous, for example: For the sequence 10,9,2,3,5,4,7,9,101,18 , wherein the LIS is 2,3,5,7,9, 18 (or 2,3,5,7,9,101 )
Then it appears the local Another thing to note: LIS itself is not necessarily only one, but LIS.length () must be fixed (it is easy to disprove, right)
[Since I was the first study to LIS, so out of their own dp analysis may be very advanced water orz]
It is better that we start from the example above it -
vector<int> nums = {10,9,2,3,5,4,7,9,101,18}
Initial: dp [0] = 1 count because only it themselves, but if we specify returned preceded no less than he would return to his place
I-th | nums[i] | A ratio nums [i] a small number of positions |
dp[i] | sequence |
0 | 10 | 0 | 1 | 10 |
1 | 9 | 1 | 1 | 9 |
2 | 2 | 2 | 1 | 2 |
3 | 3 | 2 | 2 | 2,3 |
4 | 5 | 3 | 3 | 2,3,5 |
5 | 4 | 2 | 3 | 2,3,4 |
6 | 7 | 4 | 4 | 2,3,5,7 |
7 | 9 | 6 | 5 | 2,3,5,7,9 |
8 | 101 | 7 | 6 | 2,3,5,7,9,101 |
9 | 18 | 7 | 6 | 2,3,5,7,9,18 |
Note: According to the "greed" of our needs, we are looking for one specific nums [i] a small number of locations to ensure dp corresponding figure found when the maximum
Then we need a function that returns a ratio nums [i] the position of a small number
1 vector<int> dp(10001,0);
2 int find_last_less_place(int now,vector<int>& nums,int pos)
3 {
4 int max_dp_place = pos;
5 for (int i = pos - 1; i >= 0; i--)
6 {
7 if(nums[i] < now)
8 {
9 if(dp[i] > dp[max_dp_place])
10 max_dp_place = i;
11 }
12 }
13 return max_dp_place;
14 }
Then we can deal with it overall
1 //最长上升子序列 2 int lengthOfLIS(vector<int>& nums) 3 { 4 if (nums.size() == 0) 5 return 0; 6 if (nums.size() == 1) 7 return 1; 8 9 int MAX = -1; 10 dp[0] = 1; 11 12 cout << "last = NaN" << " now_place = 0" << " now is = " << nums[0] << " dp[i] = " << 1 << endl; 13 for (int i = 1; i < nums.size(); ++i) 14 { 15 int last_place = find_last_less_place(nums[i],nums,i); 16 cout << "last = " << last_place << " now_place = " << i << " now is = " << nums[i] << " "; 17 if(last_place == i) 18 dp[i] = 1; 19 else 20 dp[i] = dp[last_place] + 1; 21 cout << "dp[i] = " << dp[i] << endl; 22 MAX = max(MAX,dp[i]); 23 } 24 return MAX; 25 }
The problem now is that the complexity of the algorithm is O (n ^ 2), the next update is when I learned to O (nlogn) of ~ the way there LICS, LCS and other issues