[剑指 offer] JT33---Ugly number (The guest officer comes in and draws a lucky number!)

The 33rd question about the offer

The topic is as follows

Insert picture description here

Idea and code

Just keep doing it,Either multiply by 2, or multiply by 3, or multiply by 5.
ugly[0]=1;//The first ugly number is 1
ugly[1]=min(1 2,1 3,1 5)=2;// 0 0 0 -->1 0 0
ugly[2] =min(2
2,1 3,1 5)=3;// 1 0 0 -->1 1 0
ugly[3]=min(2 2,2 3,1 5)=4;// 1 1 0 -->2 1 0
ugly[4]=min(3
2,2 3,1 5)=5;// 2 1 0 -->2 1 1
ugly[5]=min(3 2,2 3,2 . 5) =. 6; // 2. 1. 1 -> 2. 3. 1
Ugly [. 6] = min (. 4
2,3 3,2- . 5) =. 8; // 2. 3. 1 -> 2. 4. 1
primary analogy can Calculated all the ugly numbers

class Solution {
    
    
public:
    int GetUglyNumber_Solution(int index) {
    
    
        if(index<=0) return 0;
        vector<int> ugly(index);
        ugly[0]=1;
        int p2=0,p3=0,p5=0;
        for(int i=1;i<index;i++){
    
    
            ugly[i]=min(ugly[p2]*2,min(ugly[p3]*3,ugly[p5]*5));
            if(ugly[i]==ugly[p2]*2) p2++;
            if(ugly[i]==ugly[p3]*3) p3++;
            if(ugly[i]==ugly[p5]*5) p5++;
        }
        return ugly[index-1];
    }
};

Insert picture description here

Guess you like

Origin blog.csdn.net/qq_42136832/article/details/114882566