264. Ugly Number II 剑指offer

来源:互联网 发布:mg宣传片 知乎 编辑:程序博客网 时间:2024/06/07 06:02

Write a program to find the n-th ugly number.

Ugly numbers are positive numbers whose prime factors only include 2, 3, 5. For example, 1, 2, 3, 4, 5, 6, 8, 9, 10, 12 is the sequence of the first 10 ugly numbers.

Note that 1 is typically treated as an ugly number, and n does not exceed 1690.

找到第n个丑数。剑指offer题目

class Solution {public:    int nthUglyNumber(int n) {        vector<int> dp(n,0);        dp[0]=1;        int tx2=0,tx3=0,tx5=0;        for(int i=1;i<n;i++)        {            dp[i]=min(2*dp[tx2],min(3*dp[tx3],5*dp[tx5]));            if(dp[i]==2*dp[tx2]) tx2++;            if(dp[i]==3*dp[tx3]) tx3++;            if(dp[i]==5*dp[tx5]) tx5++;                    }        return dp[n-1];    }};



原创粉丝点击