一、问题描述
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.
二、思路
生成丑数的数组中是从小到大有序排列的,每次都选当前最小的丑数。
采用DP思想,即动态规划,递归式:ugleNumbers[i] = min{ugleNumbers[i2] * 2,ugleNumbers[i3] *3,ugleNumbers[i5] * 5},根据递归式找到最小的丑数,同时相应的将i2、i3、i5加一。
三、代码
class Solution {
public:
int nthUglyNumber(int n) {
if(n <= 0)
return 0;
int i2 = 0, i3 = 0, i5 = 0;
int c1 = 0, c2 = 0, c3 = 0;
vector<int> ugleNums(n, 0);
ugleNums[0] = 1;
for(int i = 1; i < n; ++i ){
c1 = ugleNums[i2] * 2;
c2 = ugleNums[i3] * 3;
c3 = ugleNums[i5] * 5;
int min = c1;
if(c2 < min)
min = c2;
if(c3 < min)
min = c3;
ugleNums[i] = min;
if(min == c1)
i2++;
if(min == c2)
i3++;
if(min == c3)
i5++;
}
return ugleNums[n - 1];
}
};