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

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

264. Ugly Number II -Medium

2019-11-10 20:13:06
字體:
來(lái)源:轉(zhuǎn)載
供稿:網(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個(gè)丑數(shù)。丑數(shù)是有限個(gè)2、3、5的乘積,例如1,2,3,4,5,6,8,9,10,12是前10個(gè)丑數(shù)(1是特殊的丑數(shù))。n不大于1690

Example

見題目

Solution

動(dòng)態(tài)規(guī)劃解。我剛開始考慮的是dp[i]代表i是否為丑數(shù),它的確定只需要知道dp[i % 2], dp[i % 3]和dp[i % 5],只要有一個(gè)是丑數(shù),那么dp[i]必然也是丑數(shù),然后統(tǒng)計(jì)丑數(shù)的個(gè)數(shù)直到n??墒沁@樣我沒法確定到底dp需要多大,所以需要換個(gè)思路。dp[i]應(yīng)該代表第i個(gè)丑數(shù),那么它的遞推關(guān)系該怎么找呢?其實(shí)很簡(jiǎn)單,因?yàn)橄乱粋€(gè)丑數(shù)必然是乘以2,3或5中的最小的那個(gè)數(shù),所以我們只需分別記下乘以2,乘以3,乘以5的最小的數(shù)的索引,那么 dp[i] = min(dp[index_2] * 2, dp[index_3] * 3, dp[index_5] * 5),每次得到dp[i]不要忘了更新索引就可以了(注意:因?yàn)橛锌赡躣p[index_2] * 2和dp[index_3] * 3是相等的,這種情況,兩個(gè)索引都要更新)

class Solution(object): def nthUglyNumber(self, n): """ :type n: int :rtype: int """ dp = [0] * n # 1為第一個(gè)丑數(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,因?yàn)閮蓚€(gè)值可能相等,索引都需要更新 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ā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 隆林| 六盘水市| 通州市| 鄂伦春自治旗| 赞皇县| 沁源县| 张家港市| 黄骅市| 简阳市| 当阳市| 五寨县| 黄大仙区| 南溪县| 河东区| 抚远县| 汤原县| 德清县| 抚顺县| 遵化市| 东莞市| 讷河市| 辉南县| 唐山市| 衢州市| 南丹县| 文成县| 伊吾县| 浮梁县| 中牟县| 陆川县| 米脂县| 读书| 高台县| 独山县| 都江堰市| 两当县| 通河县| 天全县| 西安市| 石家庄市| 兴业县|