Leetcode 264. Ugly Number II
@(LeetCode)[LeetCode | Algorithm | DP]
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.
Original problem is HERE.
Solution #1
Time:
O(n)
O
(
n
)
Space:
O(n)
O
(
n
)
一开始的想法是:从1开始遍历,判断每一个数是否是ugly number,最终找到第n个ugly number。看似是线性时间,实际上并不是,因为到后面相邻两个ugly number之间的距离会非常大。当n较大时,找到下一个ugly number可能会花费很多时间。所以这个想法行不通。
另一个想法就是:自动生成ugly number。直接想到的就是DP,dp[i]
就表示第i
个ugly number这个想法是可行的,难点在于如何依次生成每一个ugly number。每一个ugly number都可以生成3个不同的ugly numbers,也即dp[i] * 2
,dp[i] * 3
,dp[i] * 5
,我们可以设置3个指针依次指向乘2,乘3,乘5的index。下一个dp[i+1]
,就是取3个中最小的,并将对应的指针往前移一位。
The basic idea is generating ugly numbers by using dynamic programming, dp[i]
represents the i-th
ugly number. A critical point here is that how can we generate those ugly numbers in order, otherwise we cannot find the n-th
ugly number. Every ugly number can generate 3 different ugly numbers, i.e., dp[i] * 2
, dp[i] * 3
, dp[i] * 5
. Thereby, we need the help of 3 pointers to “sort” them. Each pointer points to the multiplier of 2, 3 and 5. During each round, we find
dp[i] = min(dp[t2] * 2, min(dp[t3] * 3, dp[t5] * 5));
and move the corresponding pointer 1-position forward.
class Solution {
public:
int nthUglyNumber(int n) {
int t2 = 0, t3 = 0, t5 = 0;
vector<int> dp(n);
dp[0] = 1;
for(int i = 1; i < n; i++){
dp[i] = min(dp[t2] * 2, min(dp[t3] * 3, dp[t5] * 5));
if(dp[i] == dp[t2] * 2)
t2++;
if(dp[i] == dp[t3] * 3)
t3++;
if(dp[i] == dp[t5] * 5)
t5++;
}
return dp.back();
}
};