题目描述:
Write a program to find the nth
super ugly number.
Super ugly numbers are positive numbers whose all prime factors are in the given prime list primes
of size k
.
Example:
Input: n = 12, primes = [2,7,13,19]
Output: 32
Explanation: [1,2,4,7,8,13,14,16,19,26,28,32] is the sequence of the first 12
super ugly numbers given primes [2,7,13,19] of size 4.
Note:
1
is a super ugly number for any givenprimes
.- The given numbers in
primes
are in ascending order. - 0 <
k
≤ 100, 0 <n
≤ 106, 0 <primes[i]
< 1000. - The nth super ugly number is guaranteed to fit in a 32-bit signed integer.
给定一个质数序列,定义一个超级丑数的因数全部来自于这个序列,求满足条件的第n大的超级丑数。这道题的原理和之前求丑数是一样的,只是之前的质数数量是固定的,可以用固定的指针解决问题,那么在这道题上我们可以定义指针的数组来进行动态规划。
class Solution {
public:
int nthSuperUglyNumber(int n, vector<int>& primes) {
int m=primes.size();
vector<int> count(m,1);
vector<int> dp(n+1,INT_MAX);
dp[1]=1;
for(int i=2;i<=n;i++)
{
for(int j=0;j<m;j++)
dp[i]=min(dp[i],dp[count[j]]*primes[j]);
for(int j=0;j<m;j++)
if(dp[i]==dp[count[j]]*primes[j]) count[j]++;
}
return dp[n];
}
};