其他分享
首页 > 其他分享> > day29

day29

作者:互联网

剑指 Offer 49. 丑数

 1)会超时,数据范围只能到1200几

 1 class Solution {
 2 public:
 3     int nthUglyNumber(int n) {
 4       int k = 0,res;
 5       for(int i = 1;;i ++){
 6          if(isUglyNum(i)) k ++;
 7          if(k == n){
 8              res = i;
 9              break;
10          }  
11       }
12       return res;
13     }
14 
15 private:
16     bool isUglyNum(int n){
17         while(n > 1){
18             int tmp = n;
19             while(n % 5 == 0)  n /= 5;
20             while(n % 3 == 0)  n /= 3;
21             while(n % 2 == 0)  n /= 2;
22             if(tmp == n) break;
23         }
24         if(n == 1)  return true;
25         return false;
26     }
27 };

 2)dp[a] * 2  、dp[b] * 3  和 dp[c] * 5 要时刻保持它们是在dp[i]后离它最近的三个数,然后每次取其中最小的一个

 https://leetcode.cn/leetbook/read/illustration-of-algorithm/9hq0r6/
 1 class Solution {
 2 public:
 3     int nthUglyNumber(int n) {
 4       int a = 0,b = 0,c = 0;
 5       int dp[n];
 6       dp[0] = 1;
 7       for(int i = 1;i < n;i ++){
 8           int l = dp[a] * 2,m = dp[b] * 3,n = dp[c] * 5;
 9           dp[i] = min(min(l,m),n);
10           if(dp[i] == l)  a ++;
11           if(dp[i] == m)  b ++;
12           if(dp[i] == n)  c ++;
13       }
14       return dp[n - 1];
15     }
16 };

 

标签:day29,int,res,++,while,return,dp
来源: https://www.cnblogs.com/balabalabubalabala/p/16519098.html