[leetcode]第十周作业

来源:互联网 发布:电脑照片合成软件 编辑:程序博客网 时间:2024/06/13 18:46

题目:< leetcode > 300. Longest Increasing Subsequence

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.


分析


求解最长递增子序列,典型的动态规划问题。

例如题中给出的例子[10, 9, 2, 5, 3, 7, 101, 18]。

对于10,它是第一个,所以dp[0]= 1;

对于9,前面没有比它小的,所以dp[1]=1;

对于2,遍历前面的10和9,没有比它小的,所以dp[2]= 1;

对于5,遍历前面的10,9,2,发现2比它小,所以能和2构成最长上升子序列,2的最长上升子序列的长度为1,所以dp[3]= dp[2]+1= 1+1= 2;

对于3,遍历前面的10,9,2,5,发现2比它小,所以能和2构成最长上升子序列,2的最长上升子序列的长度为1,所以dp[4]= dp[2]+1= 1+1= 2;

对于7,遍历前面10,9,2,5,3,发现2,5,3,比它小,找2,5,3谁的最长上升子序列长度最长,用最长值加1,dp[5]= max(dp[2]+1, dp[3]+1, dp[4] +1)= 2+1= 3;

对于101,遍历前面的10,9,2,5,3,7,发现都比它小,找前面的10,9,2,5,3,7谁的最长上升子序列最长,dp[6]= max(dp[0]+1, dp[1]+1, dp[2]+1, … , dp[5]+1)= 4;

对于18,遍历前面的10,9,2,5,3,7,101,发现10,9,2,5,3,7比它小,找这几个元素谁的最长上升子序列最长,最长值3加1,得到了3+1=4;

代码

class Solution {public:    int lengthOfLIS(vector<int>& nums) {        if(nums.size() == 0) return 0;        vector<int> dp(nums.size(), 1);        int MAX = 1;        for(int i= 0; i< nums.size(); i++){            for(int j= 0; j< i; j++){                if(nums[i]> nums[j]){                    dp[i] = max(dp[j]+1, dp[i]);                }            }            MAX = max(MAX, a[i]);  //注意最大的不一定是dp[nums.size()-1],这是一个坑,还要比较一次        }        return MAX;  //所以返回MAX,而不是dp[nums.size()-1]    }};
原创粉丝点击