website/content.en/ChapterFour/0200~0299/0264.Ugly-Number-II.md
Given an integer n, return the nth ugly number.
Ugly number is a positive number whose prime factors only include 2, 3, and/or 5.
Example 1:
Input: n = 10
Output: 12
Explanation: [1, 2, 3, 4, 5, 6, 8, 9, 10, 12] is the sequence of the first 10 ugly numbers.
Example 2:
Input: n = 1
Output: 1
Explanation: 1 is typically treated as an ugly number.
Constraints:
1 <= n <= 1690Given an integer n, find and return the nth ugly number. An ugly number is a positive integer whose prime factors only include 2, 3, and/or 5.
package leetcode
func nthUglyNumber(n int) int {
dp, p2, p3, p5 := make([]int, n+1), 1, 1, 1
dp[0], dp[1] = 0, 1
for i := 2; i <= n; i++ {
x2, x3, x5 := dp[p2]*2, dp[p3]*3, dp[p5]*5
dp[i] = min(min(x2, x3), x5)
if dp[i] == x2 {
p2++
}
if dp[i] == x3 {
p3++
}
if dp[i] == x5 {
p5++
}
}
return dp[n]
}
func min(a, b int) int {
if a < b {
return a
}
return b
}