Ugly Number II
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.
Hint:
- The naive approach is to call
isUglyfor every number until you reach the nth one. Most numbers are not ugly. Try to focus your effort on generating only the ugly ones. - An ugly number must be multiplied by either 2, 3, or 5 from a smaller ugly number.
- The key is how to maintain the order of the ugly numbers. Try a similar approach of merging from three sorted lists: L1, L2, and L3.
- Assume you have Uk, the kth ugly number. Then Uk+1 must be Min(L1 * 2, L2 * 3, L3 * 5).
解题思路
使用动态规划(Dynamic Programming)求解,代码如下:
class Solution {
public:
int nthUglyNumber(int n) {
int uglyNums[n] = {1};
int factor2 = 2, factor3 = 3, factor5 = 5;
int index2 = 0, index3 = 0, index5 = 0;
for (int i = 1; i < n; ++i) {
uglyNums[i] = min(factor2, min(factor3, factor5));
if (uglyNums[i] == factor2)
factor2 = 2 * uglyNums[++index2];
if (uglyNums[i] == factor3)
factor3 = 3 * uglyNums[++index3];
if (uglyNums[i] == factor5)
factor5 = 5 * uglyNums[++index5];
}
return uglyNums[n-1];
}
};
本文介绍了一种使用动态规划算法解决寻找第n个丑数的问题。丑数是指只能由2、3、5这三个质数作为因子的正整数,其中1通常也被认为是丑数。通过维护三个指针来生成丑数序列,并找到第n个丑数。
512

被折叠的 条评论
为什么被折叠?



