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.
从1开始,每次结果肯定是2、3、5中的一个乘出的结果,即2*x,3*y ,5*z中最小的。xyz也一定是之前乘出来的(或者是1)。
我们使用dp[n]作为记录,这样dp是个递增数列,用t2、t3、t5记录与2、3、5相乘形成最小值的位置。
对于t2、t3、t5,在一次求最小值时,被乘的数,t2或t3或t5需要更新,表明这个数已经被用成了最小值的因子。
更新也就是加一,因为dp是递增的,加一对应的dp值是当前未做因子使用的最小值。循环求到n即可。
class Solution {
public:
int nthUglyNumber(int n) {
if(n<7){
return n;
}
int t2=0,t3=0,t5=0;
vector<int> dp(n);
dp[0]=1;
for(int i=1; i<n; i++){
dp[i]=min(dp[t2]*2, min(dp[t3]*3, dp[t5]*5));
if(dp[i]==dp[t2]*2)
t2++;
if(dp[i]==dp[t3]*3)
t3++;
if(dp[i]==dp[t5]*5)
t5++;
}
return dp[n-1];
}
};