LeetCode 313. Super Ugly Number
Description
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.
描述
編寫一段程式來查詢第 n 個超級醜數。
超級醜數是指其所有質因數都是長度為 k 的質數列表 primes 中的正整數。
示例:
輸入: n = 12, primes = [2,7,13,19] 輸出: 32 解釋: 給定長度為 4 的質數列表 primes = [2,7,13,19],前 12 個超級醜數序列為:[1,2,4,7,8,13,14,16,19,26,28,32] 。
說明:
- 1 是任何給定 primes 的超級醜數。
- 給定 primes 中的數字以升序排列。
- 0 < k ≤ 100, 0 < n ≤ 106, 0 < primes[i] < 1000 。
- 第 n 個超級醜數確保在 32 位有符整數範圍內。
思路
- 這道題和第 264 題Ugly Number II 做法類似。
- 我們使用動態規劃。
- 狀態:我們用 index 用於記錄 primes 中每個質數上一次產生醜數的有效位置,並用一個數組 uglynum 記錄產生的醜數。比如 index[2] = 7, 表示質數 primes[2] 上一次產生的質數在 uglynum 中的索引為 7 ,即產生的醜數為 uglynum[7]。
- 初始值:index 所有值初始化 0,ugly 第一個值初始化為1。
- 狀態轉移方程:獲取下一個醜數:我們用 index 中記錄的上一次質數產生的醜數在 uglynum 中的位置獲得對應的醜數 uglynum[index[i]],並用對應的質數 primes[i] 與 uglynum[index[i]] 相乘作為下一次可能的醜數,所有的醜數用一個臨時陣列 _next 儲存。我們取所有數中的最小值作為下個醜數。更新 index 陣列:如果 uglynext == _next[i],我們讓 index[i] 自增一次。
- 結果:醜數陣列的最後一個值。
# -*- coding: utf-8 -*- # @Author:何睿 # @Create Date:2019-02-19 15:35:20 # @Last Modified by:何睿 # @Last Modified time: 2019-02-19 16:11:26 class Solution: def nthSuperUglyNumber(self, n: 'int', primes: 'List[int]') -> 'int': """ :type n: int :rtype: int """ # 處理特殊情況,如果n為1或者primes為空,返回1 if n < 2 or not primes: return 1 # 宣告一個數組,用於儲存獲取的醜數 uglynum = [1] # 輔助變數,primes的個數,當前生成的醜數的個數 num, count = len(primes), 1 # index陣列用於儲存primes中每個數上一次產生有效數的下一個位置 index = [0 for _ in range(num)] while count < n: # 動態規劃,用primes中的每個數從上一次產生有效位置的地方產生下一個數 _next = [primes[i] * uglynum[index[i]] for i in range(num)] # 下一個醜數是產生的醜數中最小的數 uglynext = min(_next) # 更新索引值 for i in range(num): if uglynext == _next[i]: index[i] += 1 uglynum.append(uglynext) count += 1 # 返回最後一個醜數 return uglynum[-1]
原始碼檔案在這裡 。
©本文首發於何睿的部落格 ,歡迎轉載,轉載需保留文章來源,作者資訊和本宣告.