LeetCode刷题实战313:超级丑数
共 2550字,需浏览 6分钟
·
2021-07-09 02:45
A super ugly number is a positive integer whose prime factors are in the array primes. Given an integer n and an array of integers primes, return the nth super ugly number. The nth super ugly number is guaranteed to fit in a 32-bit signed integer.
示例
输入: n = 12, primes = [2,7,13,19]
输出: 32
解释: 给定长度为 4 的质数列表 primes = [2,7,13,19],前 12 个超级丑数序列为:[1,2,4,7,8,13,14,16,19,26,28,32] 。
解题
class Solution {
public:
int nthSuperUglyNumber(int n, vector<int>& primes) {
int i, j, k = primes.size();
vector<long> idx(k,1);
vector<long long> dp(n+1, LONG_LONG_MAX);
dp[1] = 1;
for(i = 2; i <= n; ++i)
{
for(j = 0; j < k; ++j)
if(dp[idx[j]]*primes[j] < dp[i])
dp[i] = dp[idx[j]]*primes[j];
for(j = 0; j < k; ++j)
if(dp[i] == dp[idx[j]]*primes[j])
idx[j]++;
}
return dp[n];
}
};