我們把只包含因子 2、3 和 5 的數稱作醜數(Ugly Number)。求按從小到大的順序的第 n 個醜數。
示例:
輸入: n = 10
輸出: 12
解釋: 1, 2, 3, 4, 5, 6, 8, 9, 10, 12 是前 10 個醜數。
說明:
1 是醜數。
n 不超過1690。
注意:本題與主站 264 題相同:https://leetcode-cn.com/problems/ugly-number-ii/
來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/chou-shu-lcof
著作權歸領釦網絡所有。商業轉載請聯繫官方授權,非商業轉載請註明出處。
思路1:動態規劃
class Solution:
def nthUglyNumber(self, n: int) -> int:
nums = [1] * n
index1 = 0
index2 = 0
index3 = 0
for i in range(1, n):
nums[i] = min(nums[index1]*2, min(nums[index2]*3, nums[index3]*5))
# 必須分開判斷,不能用分支,因爲上面的可能有相等的情況,相等的都要加+1,例如:2*3和3*2
if nums[i] == nums[index1] * 2:
index1 += 1
if nums[i] == nums[index2] * 3:
index2 += 1
if nums[i] == nums[index3] * 5:
index3 += 1
# print(nums)
return nums[n-1]