[Leetcode] #300 Longest Increasing Subsequence

来源:互联网 发布:淘宝自动下单软件 编辑:程序博客网 时间:2024/06/11 07:08

Discription:

Given an unsorted array of integers, find the length of longest increasing subsequence.

For 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.

Your algorithm should run in O(n2) complexity.

Solution:

思路1:将数组排序后,求与原数组的最大公共子串。

思路2:动态规划。

int lengthOfLIS(vector<int>& nums) {if (nums.empty())return 0;vector<int> dp;dp.push_back(1);for (int i = 1; i < nums.size(); i++){int max_len = 1;for (int j = 0; j < i; j++){if (nums[i]>nums[j] && dp[j] + 1>max_len)max_len = dp[j] + 1;}dp.push_back(max_len);}int result = 0;for (int i = 0; i < dp.size(); i++){if (dp[i]>result)result = dp[i];}return result;}

0 0
原创粉丝点击