264. Ugly Number II

问题:

求第n个ugly number

定义:ugly number:只由2or3or5作为因数求得。

1为第一个ugly number。

Example 1:
Input: n = 10
Output: 12
Explanation: [1, 2, 3, 4, 5, 6, 8, 9, 10, 12] is the sequence of the first 10 ugly numbers.

Example 2:
Input: n = 1
Output: 1
Explanation: 1 is typically treated as an ugly number.

Constraints:
1 <= n <= 1690

  

解法:DP

1.状态:dp[i]:第i个ugly number

  • i:第i个ugly number。

2.选择:min {

  • 某个既存ugly number*2得来:dp[a]*2
  • 某个既存ugly number*3得来:dp[b]*3
  • 某个既存ugly number*5得来:dp[c]*5

}

  • a,b,c的取值:
    • 既存ugly number:那么从第一个开始,逐次递增+1
    • 当被选中,则自己递增,否则不递增(因为其值较大,可能在下一次被选中)

3.base:

  • dp[0]=1
  • a=b=c=0

 

代码参考:

 1 class Solution {
 2 public:
 3     //dp[i]:i-th ugly number
 4     //opt: min:
 5     // dp[a]*2
 6     // dp[b]*3
 7     // dp[c]*5
 8     //a,b,c=?
 9     //0...i:iteratly item ++
10     int nthUglyNumber(int n) {
11         vector<int>dp(n,0);
12         int a=0,b=0,c=0;
13         dp[0]=1;
14         for(int i=1; i<n; i++) {
15             dp[i] = min(dp[a]*2, min(dp[b]*3,dp[c]*5));
16             if(dp[i]==dp[a]*2) a++;
17             if(dp[i]==dp[b]*3) b++;
18             //notice: if dp[i]=both a, b, then a++ b++ should be done at the same time.
19             //cause, ugly number sequence also hasn't duplicated value.
20             if(dp[i]==dp[c]*5) c++;
21         }
22         return dp[n-1];
23     }
24 };

 

posted @ 2021-04-01 14:00  habibah_chang  阅读(41)  评论(0编辑  收藏  举报