Question
Write a program to find the n-th ugly number.
Ugly numbers are positive numbers whose prime factors only include 2, 3, 5. For example, 1, 2, 3, 4, 5, 6, 8, 9, 10, 12 is the sequence of the first 10 ugly numbers.
Note that 1 is typically treated as an ugly number, and n does not exceed 1690.
找到第n个丑数。丑数是有限个2、3、5的乘积,例如1,2,3,4,5,6,8,9,10,12是前10个丑数(1是特殊的丑数)。n不大于1690
Example
- 见题目
Solution
动态规划解。我刚开始考虑的是dp[i]代表i是否为丑数,它的确定只需要知道dp[i % 2], dp[i % 3]和dp[i % 5],只要有一个是丑数,那么dp[i]必然也是丑数,然后统计丑数的个数直到n。可是这样我没法确定到底dp需要多大,所以需要换个思路。dp[i]应该代表第i个丑数,那么它的递推关系该怎么找呢?其实很简单,因为下一个丑数必然是乘以2,3或5中的最小的那个数,所以我们只需分别记下乘以2,乘以3,乘以5的最小的数的索引,那么 dp[i] = min(dp[index_2] * 2, dp[index_3] * 3, dp[index_5] * 5),每次得到dp[i]不要忘了更新索引就可以了(注意:因为有可能dp[index_2] * 2和dp[index_3] * 3是相等的,这种情况,两个索引都要更新)
class Solution(object): def nthUglyNumber(self, n): """ :type n: int :rtype: int """ dp = [0] * n # 1为第一个丑数 dp[0] = 1 # 从1开始向前寻找 index_2, index_3, index_5 = 0, 0, 0 for i in range(1, n): dp[i] = min(dp[index_2] * 2, dp[index_3] * 3, dp[index_5] * 5) # 这里不要elif,因为两个值可能相等,索引都需要更新 if dp[i] == dp[index_2] * 2: index_2 += 1 if dp[i] == dp[index_3] * 3: index_3 += 1 if dp[i] == dp[index_5] * 5: index_5 += 1 return dp[n - 1]