LeetCode 264.醜數 II DP

題意:給一個整數n,求出第n個醜數,醜數即爲只包含質因數2,3,5的數
思路:把質因數分別爲2,3,5的醜數看成3個子數組,把整個dp數組看成3個子數組的組合,取每個子數組的索引L1,L2,L3,則第k個醜數即爲min(dp[L1]*2,dp[L2]*3,dp[L3]*5),若當前醜數大於某個子數組索引上的值則更新索引值,如此可求出所有n個醜數

class Solution {
    public int nthUglyNumber(int n) {
        int[] dp = new int[n+1];
        dp[0] = 1;
        int l1 = 0, l2 = 0, l3 = 0;
        for (int i = 1; i <= n; i++) {
            dp[i] = Math.min(dp[l1]*2, Math.min(dp[l2]*3, dp[l3]*5));
            if (dp[i] >= dp[l1]*2)
                l1++;
            if (dp[i] >= dp[l2]*3)
                l2++;
            if (dp[i] >= dp[l3]*5)
                l3++;
        }
        return dp[n-1];
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章