leetcode-丑数

    技术2022-07-10  91

    我们把只包含质因子 2、3 和 5 的数称作丑数(Ugly Number)。求按从小到大的顺序的第 n 个丑数。

    示例: 输入: n = 10 输出: 12 解释: 1, 2, 3, 4, 5, 6, 8, 9, 10, 12 是前 10 个丑数。

    说明: 1 是丑数。 n 不超过1690。

    直接代码速记吧,这道题的官方解释太长了我也没看懂…

    #include<iostream> #include<string> #include<vector> #include<algorithm> #include<unordered_set> using namespace std; class Solution { public: int nthUglyNumber(int n) { vector<int>dp(n,1); int a=0,b=0,c=0; for(int i=1;i<n+1;++i){ int n2=dp[a]*2,n3=dp[b]*3,n5=dp[c]*5; dp[i]=min(n2,n3,n5); if(dp[i]==n2)n2++; if(dp[i]==n3)n3++; if(dp[i]==n5)n5++; } return dp[n]; } };

    Processed: 0.012, SQL: 9