题目:
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.
解答:
通过分析不难发现所有的ugly数字,只能是有由这些prime相乘得到,所以最终的第n个就是这些prime之间所有的相乘的可能值排序后的第n个
代码实现如下(一开始看不懂的用例子模拟一下操作就会比较容易懂),注意1不是素数
class Solution {
public:
int nthSuperUglyNumber(int n, vector<int>& primes) {
vector<int> ugly(n, 0);
ugly[0] = 1;
vector<int> factor = primes;
int size = primes.size();
vector<int> index(size, 0);
for (int i = 1; i < n; ++i)
{
int tmp = factor[0];
for (int j = 1; j < size; ++j)
{
if (factor[j] < tmp)
{
tmp = factor[j];
}
}
ugly[i] = tmp;
for(int j = 0; j < size; ++j)//为了防止在过程中出现两个相同的数字,而导致ugly重复,需要进行整个的遍历
{
if(factor[j] == tmp)
factor[j] = primes[j] * ugly[++index[j]];
}
}
return ugly[n - 1];
}
};