LeetCode: 313. Super Ugly Number
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 given primes.
- 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.
解题思路
- 动态规划的思路:ugly number = ugly number * primes
- 记录每个
primes
下一次应该用的 ugly number。每次选择最小的 ugly number * primes 作为新的 ugly number
AC 代码
func min(lhv, rhv int) int {
if lhv < rhv {
return lhv
} else {
return rhv
}
}
func nthSuperUglyNumber(n int, primes []int) int {
var uglynum []int // 记录前 n 个 uglynum
var records []int // records[i] 记录下一个需要乘以 primes[i] 的 uglynum 的下标
//初始化:
// 第一个 ugly number 是 1
uglynum = append(uglynum, 1)
// 一开始所有的 primes 下一个要乘的数都是下标为 0 的ugly number
for i := 0; i < len(primes); i++ {
records = append(records, 0)
}
for i := 1; i < n; i++ {
for j := 0; j < len(primes); j++ {
cur := primes[j]*uglynum[records[j]]
if cur == uglynum[i-1] { // 上一个循环用过的 primes
records[j]++
cur = primes[j]*uglynum[records[j]]
}
if j == 0 { // 下一个 ugly number
uglynum = append(uglynum, cur)
} else {
uglynum[i] = min(uglynum[i], cur)
}
}
}
return uglynum[n-1]
}