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
. For example, [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) 1
is a super ugly number for any given primes
.
(2) The given numbers in primes
are in ascending order.
(3) 0 < k
≤ 100, 0 < n
≤ 106, 0 < primes[i]
< 1000.
(4) The nth super ugly number is guaranteed to fit in a 32-bit signed integer.
这个题目与丑数类似,只是增加了候选公约数的数目.将原来的候选数组改成矩阵。
思路1:下面的编程非常巧妙,去除了重复因子
class Solution {
public:
int nthSuperUglyNumber(int n, vector<int>& primes) {
vector<int> dp(n,0);
vector<int> idx(primes.size(),0);//保存每个候选因子的当前乘积下标
vector<int> val(primes.size(),1);//保存当前因子的乘积
dp[0]=1;
int next=1;
for(int i=0;i<n;i++)
{
dp[i]=next;
next=numeric_limits<int>::max();
for(int j=0;j<primes.size();j++)
{
if(dp[i]==val[j]) val[j]=primes[j]*dp[idx[j]++];
next=min(next,val[j]);
}
}
return dp[n-1];
}
};
思路2:使用优先级队列
class Solution {
public:
int nthSuperUglyNumber(int n, vector<int>& primes) {
priority_queue<num,vector<num>,comp> q;
for(int i=0;i<primes.size();i++)
{
q.emplace(primes[i],1,primes[i]);
}
vector<int> res(n,0);
res[0]=1;
for(int i=1;i<n;i++)
{
res[i]=q.top().val;
while(q.top().val==res[i])
{
num temp=q.top();
q.pop();
q.emplace(res[temp.idx]*temp.p,temp.idx+1,temp.p);
}
}
return res[n-1];
}
struct num{
int val;//当前因子的下一个候选值
int idx;//当前因子的下标
int p;//当前因子
num(int a,int b,int c):val(a),idx(b),p(c){
}
};
struct comp{
bool operator()(const num& a,const num& b){
return a.val>b.val;
}
};
};