问题描述:
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.
问题分析:
本题分析与Super Ugly Number一样,这里就不多说了,详戳http://blog.csdn.net/u011809767/article/details/78351462
过程详见代码:
class Solution {
public:
int nthUglyNumber(int n) {
vector<int> dp(n, INT_MAX), p{2,3,5},idx(3,0);
dp[0] = 1;
for (int i = 1; i < n; i++)
{
for (int j = 0; j < 3; j++)
{
dp[i] = min(dp[i], dp[idx[j]] * p[j]);
}
for (int j = 0; j < 3; j++)
{
while (dp[idx[j]] * p[j] <= dp[i]) idx[j]++;
}
}
return dp[n - 1];
}
};