题目描述:
Write a program to find the n
-th ugly number.
Ugly numbers are positive numbers whose prime factors only include 2, 3, 5
.
Example:
Input: n = 10
Output: 12
Explanation: 1, 2, 3, 4, 5, 6, 8, 9, 10, 12 is the sequence of the first 10 ugly numbers.
Note:
1
is typically treated as an ugly number.n
does not exceed 1690.
根据丑数的定义找到第n大的丑数。由于丑数的因数只包含2或3或5,那么较大的丑数自然是由较小的丑数迭代得到的。定义三个指针和一个动态规划数组,三个指针分别指向上一次倍乘2、3、5的较小的丑数,那么当前的丑数就是之前的指向的较小丑数倍乘2、3、5得到的最小值。
class Solution {
public:
int nthUglyNumber(int n) {
vector<int> dp(n+1,0);
dp[1]=1;
int j=1;
int k=1;
int l=1;
for(int i=2;i<=n;i++)
{
dp[i]=min(min(dp[j]*2,dp[k]*3),dp[l]*5);
if(dp[i]==dp[j]*2) j++;
if(dp[i]==dp[k]*3) k++;
if(dp[i]==dp[l]*5) l++;
}
return dp[n];
}
};