[LeetCode] Ugly Number II

264. Ugly Number II

An ugly number is a positive integer whose prime factors are limited to 2, 3, and 5.

Given an integer n, return the nth ugly number.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution {
public:
int nthUglyNumber(int n) {
vector<int> dp(n);
dp[0] = 1;
int two = 0, three = 0, five = 0;
for(int i = 1; i < n; i++) {
dp[i] = min({2*dp[two], 3*dp[three], 5*dp[five]});
if(dp[i] == 2*dp[two]) two++;
if(dp[i] == 2*dp[three]) three++;
if(dp[i] == 2*dp[five]) five++;
}
return dp.back();
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/02/11/PS/LeetCode/ugly-number-ii/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.