zoukankan      html  css  js  c++  java
  • 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 };
  • 相关阅读:
    [LeetCode 220.] 存在重复元素 III
    C++ 构造函数 & 析构函数
    [LeetCode 891.] 子序列宽度之和【hard】
    [LeetCode 447.] Number of Boomerangs
    HJ93 数组分组
    HJ77 火车进站
    [LeetCode 338.] 比特位计数
    线段树
    大数量问题的一般解决方法
    字典树
  • 原文地址:https://www.cnblogs.com/habibah-chang/p/14606035.html
Copyright © 2011-2022 走看看