[Dynamic Programming] leetcode 264 Ugly Number II

problem: https://leetcode.com/problems/ugly-number-ii

        Ugly number is larger by a small ugly number multiplied by a factor 2, 3, 5 is obtained, after each multiplication, taken as a minimum, and the minimum value of the current pointer back one move. (With vector package a bit more slowly, and is not the case as long as 4ms)

class Solution {
public:
    int nthUglyNumber(int n) {
        vector<int> dp(n + 1);
        dp[1] = 1;
        vector<int> idx {1, 1, 1};
        vector<int> nums {2, 3, 5};
        for(int i = 2;i <= n;i++)
        {
            vector<int> res(nums.size());
            int min_num = INT_MAX;
            for(int j = 0;j < nums.size();j++)
            {
                res[j] = nums[j] * dp[idx[j]];
                min_num = min(min_num, res[j]);
            }
            for(int j = 0;j < nums.size();j++)
            {
                if(res[j] == min_num)
                {
                    idx[j]++;
                }
            }
            dp[i] = min_num;
        }
        return dp[n];
    }
};

 

Guess you like

Origin www.cnblogs.com/fish1996/p/11331321.html