天天看點

leetcode-dp-最長遞增子序列

import java.util.Arrays;

/**
<p>給你一個整數數組 <code>nums</code> ,找到其中最長嚴格遞增子序列的長度。</p>

<p><strong>子序列 </strong>是由數組派生而來的序列,删除(或不删除)數組中的元素而不改變其餘元素的順序。例如,<code>[3,6,2,7]</code> 是數組 <code>[0,3,1,6,2,2,7]</code> 的子序列。</p>
 

<p><strong>示例 1:</strong></p>

<pre>
<strong>輸入:</strong>nums = [10,9,2,5,3,7,101,18]
<strong>輸出:</strong>4
<strong>解釋:</strong>最長遞增子序列是 [2,3,7,101],是以長度為 4 。
</pre>

<p><strong>示例 2:</strong></p>

<pre>
<strong>輸入:</strong>nums = [0,1,0,3,2,3]
<strong>輸出:</strong>4
</pre>

<p><strong>示例 3:</strong></p>

<pre>
<strong>輸入:</strong>nums = [7,7,7,7,7,7,7]
<strong>輸出:</strong>1
</pre>

<p> </p>

<p><strong>提示:</strong></p>

<ul>
    <li><code>1 <= nums.length <= 2500</code></li>
    <li><code>-10<sup>4</sup> <= nums[i] <= 10<sup>4</sup></code></li>
</ul>

<p> </p>

<p><b>進階:</b></p>

<ul>
    <li>你能将算法的時間複雜度降低到 <code>O(n log(n))</code> 嗎?</li>
</ul>
<div><div>Related Topics</div><div><li>數組</li><li>二分查找</li><li>動态規劃</li></div></div><br><div><li>👍 2599</li><li>👎 0</li></div>
*/

//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
    public 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;
    }
}
//leetcode submit region end(Prohibit modification and deletion)