Write a program to find the n
-th ugly number.
Ugly numbers are positive numbers whose prime factors only include 2, 3, 5
. For example, 1,
2, 3, 4, 5, 6, 8, 9, 10, 12
is the sequence of the first 10
ugly numbers.
Note that 1
is typically treated as an ugly number, and n does
not exceed 1690.
动态规划:
public class Solution {
public int nthUglyNumber(int n) {
int[] dp=new int[n];
dp[0]=1;
int num2=0,num3=0,num5=0;
for(int i=2;i<=n;i++){
dp[i-1]=Math.min(dp[num2]*2, Math.min(dp[num3]*3, dp[num5]*5));
if(dp[i-1]==dp[num2]*2) num2++;
if(dp[i-1]==dp[num3]*3) num3++;
if(dp[i-1]==dp[num5]*5) num5++;
}
return dp[n-1];
}
}