1. 程式人生 > >【LeetCode & 劍指offer刷題】動態規劃與貪婪法題10:Longest Increasing Subsequence

【LeetCode & 劍指offer刷題】動態規劃與貪婪法題10:Longest Increasing Subsequence

rst 貪婪 float tor leet rep 大於等於 lower ola

【LeetCode & 劍指offer 刷題筆記】目錄(持續更新中...)

Longest Increasing Subsequence

Given an unsorted array of integers, find the length of longest increasing subsequence. Example: Input: [10,9,2,5,3,7,101,18] Output: 4 Explanation: The longest increasing subsequence is [2,3,7,101], therefore the length is 4
. Note:
  • There may be more than one LIS combination, it is only necessary for you to return the length.
  • Your algorithm should run in O(n2) complexity.
Follow up: Could you improve it to O(n log n) time complexity?
C++ //問題:找最長遞增子序列(可以不要求連續) /* 方法:動態規劃 dp[i]表示以nums[i]為結尾的最長遞增子串的長度 dp[i] = max(dp[i], dp[j] + 1)
O(n^2) O(n) */ class Solution { public: int lengthOfLIS(vector<int>& nums) { vector<int> dp(nums.size(), 1); //dp值初始化為1,dp[0] = 1,一個元素長度為1 int res = 0; for (int i = 0; i < nums.size(); i++) //遍歷數組,以num[i]結尾 { for (int j
= 0; j < i; j++) //遍歷num[i]以前的數(i=0~n-1,j=0~i-1) { if (nums[j] < nums[i] )//當遇到遞增對時,dp[j]+1,更新dp[i] dp[i] = max(dp[i], dp[j] + 1); } res = max(res, dp[i]); //選擇dp[i]中的最大值,因為不確定以哪個num[i]結尾的遞增子序列最長 } return res; } }; /* 掌握 * 方法:動態規劃+二分查找 * 具體過程:dp存最長遞增子序列 註意:數組dp不一定是真實的LIS,只是長度一致 * 例: input: [0, 8, 4, 12, 2] dp: [0] dp: [0, 8] dp: [0, 4] dp: [0, 4, 12] dp: [0 , 2, 12] which is not the longest increasing subsequence, but length of dp array results in length of Longest Increasing Subsequence. * O(nlogn) O(n) 類似問題: Increasing Triplet Subsequence */ #include <algorithm> class Solution { public: int lengthOfLIS(vector<int>& a) { if(a.empty()) return 0; vector<int> dp; for (int ai : a) { //lower_bound返回第一個大於等於ai的位置,函數參數為(first,last) last指向區間末尾位置 //在dp[first,last)序列中尋找ai可以滿足增序插入的位置,如果找不到,說明ai比區間所有值大,返回last //因為dp維護成一個增序數組,故可用二分查找法 auto it = lower_bound(dp.begin(), dp.end(), ai); //查找第一個大於等於ai的位置(查找ai可以插入的位置) if (it == dp.end()) //如果區間中不存在,則push到末尾 dp.push_back(ai); else //如果存在,則替換對應位置的元素 *it = ai; } return dp.size(); } };

【LeetCode & 劍指offer刷題】動態規劃與貪婪法題10:Longest Increasing Subsequence