您的位置:首页 > 其它

Ugly Number II问题及解法

2017-10-26 15:20 183 查看
问题描述:

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.
问题分析:

本题分析与Super Ugly Number一样,这里就不多说了,详戳http://blog.csdn.net/u011809767/article/details/78351462

过程详见代码:

class Solution {
public:
int nthUglyNumber(int n) {
vector<int> dp(n, INT_MAX), p{2,3,5},idx(3,0);
dp[0] = 1;
for (int i = 1; i < n; i++)
{
for (int j = 0; j < 3; j++)
{
dp[i] = min(dp[i], dp[idx[j]] * p[j]);
}
for (int j = 0; j < 3; j++)
{
while (dp[idx[j]] * p[j] <= dp[i]) idx[j]++;
}
}
return dp[n - 1];
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: