超级丑数 Super Ugly Number
LeetCode传送门313. Super Ugly Number
题目
超级丑数 是一个正整数,并满足其所有质因数都出现在质数数组 primes 中。
给你一个整数 n 和一个整数数组 primes ,返回第 n 个 超级丑数 。
题目数据保证第 n 个 超级丑数 在 32-bit 带符号整数范围内。
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.
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].
Input: n = 1, primes = [2,3,5]
Output: 1
Explanation: 1 has no prime factors, therefore all of its prime factors are in the array primes = [2,3,5].
Constraints:
1 <= n <= 10^6 1 <= primes.length <= 100 2 <= primes[i] <= 1000 primes[i] is guaranteed to be a prime number. All the values of primes are unique and sorted in ascending order.
思考线
解题思路
本道题是上一篇文章的升级版,也是用动态规划去解决,只不过我们小心的去处理primes中对应pd中的下标。
如果学会了上一篇 丑数II,这个部分的代码就呼之欲出,直接上代码
function nthSuperUglyNumber(n: number, primes: number[]): number {
const pivot:number[] = new Array(primes.length).fill(1);
const pd = [0,1];
console.log(pivot)
for(let i = 2; i <=n;i++) {
let min = Infinity;
const res = pivot.map((item, index) => {
const r = pd[item] * primes[index];
if(r<=min) {
min = r;
}
return r;
});
pd[i] = min;
res.forEach((item, index) => {
if(item === min) {
pivot[index]++;
}
})
}
return pd[n];
};
这就是我对本题的解法,如果有疑问或者更好的解答方式,欢迎留言互动。