剑指 Offer 49. 丑数
我们把只包含质因子 2、3 和 5 的数称作丑数(Ugly Number)。求按从小到大的顺序的第 n 个丑数。
思路
方法一:堆 + 哈希去重
方法二:动态规划
代码
堆 + 哈希去重
typedef long long ll;
class Solution {
public:
int nthUglyNumber(int n) {
ll factors[3] = {2, 3, 5};
unordered_set<ll> seen;
priority_queue<ll, vector<ll>, greater<ll>> q;
q.push(1ll);
seen.insert(1ll);
ll cur;
for (int i = 0; i < n; ++i) {
cur = q.top();
q.pop();
for (int j = 0; j < 3; ++j) {
ll temp = cur * factors[j];
if (!seen.count(temp)) {
q.push(temp);
seen.insert(temp);
}
}
}
return cur;
}
};
动态规划
class Solution {
public:
int nthUglyNumber(int n) {
int a = 0, b = 0, c = 0;
int dp[n];
dp[0] = 1;
for(int i = 1; i < n; i++) {
int n2 = dp[a] * 2, n3 = dp[b] * 3, n5 = dp[c] * 5;
dp[i] = min(min(n2, n3), n5);
if(dp[i] == n2) a++;
if(dp[i] == n3) b++;
if(dp[i] == n5) c++;
}
return dp[n - 1];
}
};