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.
每次筛选出下一个ugly数,运用DP
public class Solution {
public int nthUglyNumber(int n) {
int[] ugly = new int[n];
ugly[0] = 1;
int fact2 = 2, fact3 = 3, fact5 = 5;
int index2 = 0, index3 = 0, index5 = 0;
for(int i=1; i<n; i++){
int min = Math.min(Math.min(fact2, fact3), fact5);
ugly[i] = min;
if(min==fact2) fact2 = 2*ugly[++index2];
if(min==fact3) fact3 = 3*ugly[++index3];
if(min==fact5) fact5 = 5*ugly[++index5];
}
return ugly[n-1];
}
}