我们把只包含因子 2、3 和 5 的数称作丑数(Ugly Number)。求按从小到大的顺序的第 n 个丑数。
示例:
输入: n = 10
输出: 12
解释: 1, 2, 3, 4, 5, 6, 8, 9, 10, 12 是前 10 个丑数。
说明:
1 是丑数。
n 不超过1690。
注意:本题与主站 264 题相同:https://leetcode-cn.com/problems/ugly-number-ii/
class Solution {
public:
int nthUglyNumber(int n) {
vector<int> f(n, 1);
int twos = 0, threes = 0, fives = 0;
for (int i = 1; i < n; ++i)
{
f[i] = min(min(f[twos] * 2, f[threes] * 3), f[fives] * 5);
if (f[i] == f[twos] * 2)
++twos;
if (f[i] == f[threes] * 3)
++threes;
if (f[i] == f[fives] * 5)
++fives;
}
return f[n - 1];
}
};