LeetCode的第264道题目,编写程序以查找第n个丑数。
丑数是正数,其因数仅包括2, 3, 5。
动态规划来做,每个丑数必定是前面丑数×2,×3或者×5得来,维护三个指针,依次向前求解,代码如下:
public int nthUglyNumber(int n) {
return nthUglyNumber(n,2,3,5);
}
public static int nthUglyNumber(int n,int a,int b,int c) {
int[] dp = new int[n + 1];
dp[1] = 1;
int p1 = 1, p2 = 1, p3 = 1;
for (int i = 2; i <= n; i++) {
dp[i] = Math.min(dp[p1] * a, Math.min(dp[p2] * b, dp[p3] * c));
if (dp[i] == dp[p1] * a)
p1++;
if (dp[i] == dp[p2] * b)
p2++;
if (dp[i] == dp[p3] * c)
p3++;
}
return dp[n];
}