国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學(xué)院 > 開發(fā)設(shè)計 > 正文

264. Ugly Number II -Medium

2019-11-10 19:18:27
字體:
供稿:網(wǎng)友

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個丑數(shù)。丑數(shù)是有限個2、3、5的乘積,例如1,2,3,4,5,6,8,9,10,12是前10個丑數(shù)(1是特殊的丑數(shù))。n不大于1690

Example

見題目

Solution

動態(tài)規(guī)劃解。我剛開始考慮的是dp[i]代表i是否為丑數(shù),它的確定只需要知道dp[i % 2], dp[i % 3]和dp[i % 5],只要有一個是丑數(shù),那么dp[i]必然也是丑數(shù),然后統(tǒng)計丑數(shù)的個數(shù)直到n??墒沁@樣我沒法確定到底dp需要多大,所以需要換個思路。dp[i]應(yīng)該代表第i個丑數(shù),那么它的遞推關(guān)系該怎么找呢?其實很簡單,因為下一個丑數(shù)必然是乘以2,3或5中的最小的那個數(shù),所以我們只需分別記下乘以2,乘以3,乘以5的最小的數(shù)的索引,那么 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為第一個丑數(shù) 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]
發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 拜泉县| 阿城市| 永川市| 鲁山县| 邵阳县| 永康市| 垦利县| 永顺县| 武义县| 桦南县| 从江县| 伊宁县| 洮南市| 青铜峡市| 秦皇岛市| 锡林郭勒盟| 舟曲县| 本溪| 灵川县| 潜山县| 右玉县| 吐鲁番市| 巧家县| 斗六市| 扎囊县| 报价| 吴桥县| 望城县| 茌平县| 环江| 中宁县| 合阳县| 横山县| 琼结县| 项城市| 福清市| 岑巩县| 昌平区| 富川| 平顺县| 固安县|