673. Number of Longest Increasing Subsequence
文章目錄
- 1 題目理解
- 2 動態規劃
1 題目理解
Given an integer array nums, return the number of longest increasing subsequences.
Notice that the sequence has to be strictly increasing.
輸入:整數數組int[] nums
輸出:最長遞增子序列的個數
規則:子序列是指從原數組中找出若干元素組成新的數組。這些元素不一定是下標相鄰的,但是元素前后順序不能變。遞增子序列就是新的子數組中,i>j,a[i]>=a[j]。
2 動態規劃
我們用dp[i]來記錄以第i個元素為結尾的最長遞增子序列的長度。
那么設j=0,1,2…i-1,當nums[i]>nums[j]的時候,dp[j]+1就是一個可能的值。從這些值中取最大值,就是dp[i]的值。
同時我們用count[i]記錄以nums[i]為結尾的最長遞增子序列有多少個。
例如nums=[1,3,5,4,7];
處理第0個元素1:dp[0]=1,count[0]=1
處理第1個元素3:3>1,dp[1]=2,count[1]=count[0]=1
處理第2個元素5:5>1,dp[2]=2,count[2]=count[0]=1
5>3,dp[1]+1>dp[2],所以更新dp[2]=3,count[2]=count[1]=1
…
所以當遇到dp[j]+1>dp[i]的時候,count[i]=count[j],當遇到dp[j]+1==dp[i]的時候,count[i] +=count[j]。做疊加。
總結
以上是生活随笔為你收集整理的673. Number of Longest Increasing Subsequence的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Hadoop Mapreduce分区、分
- 下一篇: Leetcode五大常用算法