Sword Finger Offer Interview Question 49. Ugly Number [Medium]-Dynamic Programming

The same problem as LeetCode264.

My solution:

Points to note:

(1) 1 is also an ugly number

(2) When determining who increments abc, use if instead of else if, because it is possible that dp [i] is the result of multiple numbers multiplied by factors

class Solution {
public:
    int nthUglyNumber(int n) {
        if(n<7) return n;
        int *dp=new int[n];
        int a=0,b=0,c=0;
        dp[0]=1;
        int i=1;
        while(i<n){
            dp[i]=min({2*dp[a],3*dp[b],5*dp[c]});
            if(dp[i]==2*dp[a])  a++;
            if(dp[i]==3*dp[b])  b++;
            if(dp[i]==5*dp[c])  c++;
            i++;
        }
        return dp[n-1];
    }
};

Published 65 original articles · Like1 · Visits 488

Guess you like

Origin blog.csdn.net/qq_41041762/article/details/105459508