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

    数学归纳法

    package dp.lengthOfLIS;
    
    import java.util.Arrays;
    
    /**
     * 300. 最长递增子序列
     * 给你一个整数数组 nums ,找到其中最长严格递增子序列的长度。
     *
     * 子序列是由数组派生而来的序列,删除(或不删除)数组中的元素而不改变其余元素的顺序。例如,[3,6,2,7] 是数组 [0,3,1,6,2,2,7] 的子序列。
     *
     *
     * 示例 1:
     *
     * 输入:nums = [10,9,2,5,3,7,101,18]
     * 输出:4
     * 解释:最长递增子序列是 [2,3,7,101],因此长度为 4 。
     * 示例 2:
     *
     * 输入:nums = [0,1,0,3,2,3]
     * 输出:4
     * 示例 3:
     *
     * 输入:nums = [7,7,7,7,7,7,7]
     * 输出:1
     *
     *
     * 提示:
     *
     * 1 <= nums.length <= 2500
     * -104 <= nums[i] <= 104
     *
     *
     * 进阶:
     *
     * 你可以设计时间复杂度为 O(n2) 的解决方案吗?
     * 你能将算法的时间复杂度降低到 O(n log(n)) 吗?
     */
    public class lengthOfLIS {
        /**
         * 
         * 动态规划-数学归纳法
         * 解题思路:每一个dp【i】要和之前的数组元素比较,判断比几个大 这就是 max(dp[i],dp[j]+1)的含义;
         * @param nums
         * @return
         */
        public static int lengthOfLIS(int[] nums) {
            int[] dp = new int[nums.length];
            Arrays.fill(dp,1);
            for (int i = 0; i < nums.length; i++) {
                for (int j = 0; j < i; j++) {
                    if(nums[i]>nums[j]){
                        dp[i]=Math.max(dp[i],dp[j]+1);
                    }
                }
            }
    
            int res = 0;
            for (int i = 0; i < dp.length; i++) {
                res = Math.max(res,dp[i]);
            }
            return res;
        }
    
        public static void main(String[] args) {
            int[] nums = {1,4,3,4,2,3};
            System.out.println(lengthOfLIS(nums));
        }
    }
    
    
    不会,我可以学;落后,我可以追赶;跌倒,我可以站起来!
  • 相关阅读:
    P4363 [九省联考2018]一双木棋chess 状压DP
    P5290 [十二省联考2019] 春节十二响 贪心
    P3747 [六省联考2017]相逢是问候 欧拉公式
    P5443 [APIO2019]桥梁 操作分块+可撤销并查集
    P4146 序列终结者 FHQ_TREAP
    108. Convert Sorted Array to Binary Search Tree
    神经网络中Epoch、Iteration、Batchsize相关理解
    905. Sort Array By Parity
    100. Same Tree
    538. Convert BST to Greater Tree
  • 原文地址:https://www.cnblogs.com/xiaoshahai/p/15714657.html
Copyright © 2011-2022 走看看