leetcode dynamic programming

简介: 300. Longest Increasing SubsequenceQuestionGiven an unsorted array of integers, find the length of longest increasing subsequence.

300. Longest Increasing Subsequence

Question

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.

Follow up: Could you improve it to O(n log n) time complexity?

Solution

dp[i] means the length of an increase sequence that includes nums[i], and it must equals a previous dp value add one which reaches the max.

class Solution(object):
    def lengthOfLIS(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        dp = [1]*len(nums)
        for i in xrange(len(nums)):
            for y in xrange(i):
                if nums[i] >nums[j]:
                    dp[i] = max(dp[i],dp[j]+1)
        return max(dp) if dp else 0
目录
相关文章
|
28天前
|
算法 安全 编译器
【C++20 新特性Concepts 概念】C++20 Concepts: Unleashing the Power of Template Programming
【C++20 新特性Concepts 概念】C++20 Concepts: Unleashing the Power of Template Programming
45 0
|
13天前
|
机器人
动态规划Dynamic Programming
动态规划Dynamic Programming
12 0
|
13天前
|
机器学习/深度学习 存储 算法
算法·动态规划Dynamic Programming
算法·动态规划Dynamic Programming
10 0
|
6月前
|
存储 算法 Python
Dynamic Programming,简称 DP
动态规划(Dynamic Programming,简称 DP)是一种在数学、计算机科学和经济学中使用的,通过把原问题分解为相对简单的子问题的方式求解复杂问题的方法。动态规划的核心思想是,将问题分解成若干个子问题,通过求解子问题并将子问题的解存储起来,以便在需要时可以重复使用,从而避免了重复计算,提高了算法的效率
60 3
|
机器学习/深度学习 算法
Data Structures and Algorithms (English) - 7-28 Review of Programming Contest Rules(30 分)
Data Structures and Algorithms (English) - 7-28 Review of Programming Contest Rules(30 分)
175 0
Data Structures and Algorithms (English) - 7-28 Review of Programming Contest Rules(30 分)
|
存储 算法 安全
动态规划(Dynamic Programming)
DP是解决多阶段决策过程中最优化问题的一种常用方法,它在算法中的重要性不言而喻,本文将帮助大家简单了解DP。
119 0
动态规划(Dynamic Programming)
|
JavaScript Java Go
Rise of Kotlin: The Programming Language for the Next Generation
Rise of Kotlin: The Programming Language for the Next Generation https://hackernoon.
1518 0