Special Leetcode of dynamic programming (DP) -264. Ugly Number II (Ugly Number II)
Write a program to find the first n
one ugly number.
Ugly is the number contains only prime factors 2, 3, 5
of positive integers.
Example:
Input: n = 10
Output: 12
Explanation: The 1, 2, 3, 4, 5, 6, 8, 9, 10, 12
first 10 ugly number.
Description:
1
Is the number of ugly.n
Not more than 1690.
dp meaning:
dp [i] denotes the i-1 th number of ugly.
class Solution { public int nthUglyNumber(int n) { int[] dp = new int[n + 1]; dp[0] = 1; int i2 = 0; int i3 = 0; int i5 = 0; for (int i = 1; i < n + 1; i++) { dp[i] = Math.min(Math.min(dp[i2] * 2, dp[i3] * 3), dp[i5] * 5); if (dp[i] == dp[i2] * 2) { i2++; } if (dp[i] == dp[i3] * 3) { i3++; } if (dp[i] == dp[i5] * 5) { i5++; } } return dp[n - 1]; } }