zoukankan      html  css  js  c++  java
  • leetcode最长递增子序列问题

    题目描写叙述:

    给定一个数组,删除最少的元素,保证剩下的元素是递增有序的。

    分析:

    题目的意思是删除最少的元素。保证剩下的元素是递增有序的,事实上换一种方式想,就是寻找最长的递增有序序列。解法有非常多种,这里考虑用动态规划实现。

    开辟一个额外的一维数组dp[]用来记录以每一个元素为结尾的最长子序列的长度。当然。还须要一个哈希表,用来保存最长子序列的元素。dp[i]表示以数组A[i]为结尾的最长子序列的长度。则不难得到例如以下的公式:

    然后通过回溯哈希表把须要删除的元素删除就可以。

    <span style="color:#000000;background-color: rgb(204, 204, 204);">public class Solution {
    	ArrayList<Integer> minDelete(int A[]){
    		ArrayList<Integer> res=new ArrayList<Integer>();
    		HashMap<Integer, Integer> hash =new HashMap<Integer, Integer>();
    		int dp[]=new int[A.length];//dp[i]记录以A[i]为结尾的最长递增子序列长度
    		int count=0;
    		int end=0;//最长递增子序列的最后一个元素
    		for(int i=0;i<A.length;i++){
    			dp[i]=1;
    			for(int j=0;j<i;j++){
    				if(A[i]>=A[j]){
    					dp[i]=Math.max(dp[i], dp[j]+1);
    					if(count<dp[i]){
    						count=dp[i];
    						hash.put(i, j);
    						end=i;
    					}
    				}
    			}
    		}
    		int k=A.length-1;
    		while(k>=0){
    			while(k>end){//增加须要被删除的元素
    				res.add(A[k]);
    				k--;
    				}
    			k--;
    			if(hash.containsKey(end)){
    				end=hash.get(end);
    				}
    				else
    					end=-1;
    		}
    		return res;
    	}
    }</span>


     

    Google了一下最长递增子序列,发现了一篇非常棒的博客,写得非常具体。

    http://blog.csdn.net/joylnwang/article/details/6766317

    并且该博客还给出了更加优化的解法,太棒了,这里mark一下。

  • 相关阅读:
    Path Sum II
    Convert Sorted Array to Binary Search Tree
    Construct Binary Tree from Inorder and Postorder Traversal
    Construct Binary Tree from Preorder and Inorder Traversal
    Maximum Depth of Binary Tree
    Binary Tree Zigzag Level Order Traversal
    Binary Tree Level Order Traversal
    Same Tree
    Validate Binary Search Tree
    Binary Tree Inorder Traversal
  • 原文地址:https://www.cnblogs.com/zhchoutai/p/6848979.html
Copyright © 2011-2022 走看看