1. 程式人生 > >[leetcode]264. Ugly Number II

[leetcode]264. Ugly Number II

Solution 1: 參照數學質因子的定義,大概規模能跑到800,900,就會超時

我這個方法也太暴力了。
https://blog.csdn.net/fulishafulisha/article/details/79984101

class Solution {
    public int nthUglyNumber(int n) {
        int count=0;
        int i=1; //Ugly numbers are positive numbers
       while(count<n){
           
           if(help(i,2)) count++;
           i++;

       }
        
        return i-1;
    }
    
    public boolean help(int i,int k){
        
        while(k<=i){ 
            if(i == k){
                return true;
            }
            else if(i%k == 0){
                i = i/k;
            }
            else{
                k++; 
                if(k>5)return false;
            }
            
        }
         return true;
    }
}

Solution 2: 用迭代,保證每次新數都是uglynumber。就能免去我一個一個找,然後還要用help函式判定。

https://leetcode.com/problems/ugly-number-ii/discuss/69364/My-16ms-C%2B%2B-DP-solution-with-short-explanation