We call numbers that only contain prime factors 2, 3, and 5 as Ugly Numbers. Find the nth ugly number in ascending order.
Example:
输入: n = 10
输出: 12
解释: 1, 2, 3, 4, 5, 6, 8, 9, 10, 12 是前 10 个丑数。
Description:
1 is an ugly number.
n does not exceed 1690.
Note: This question is the same as the main site 264 question: https://leetcode-cn.com/problems/ugly-number-ii/
Problem-solving ideas:
class Solution {
public:
int nthUglyNumber(int n) {
int a = 0, b = 0, c = 0;
int dp[n];
dp[0] = 1;
for(int i = 1; i < n; i++) {
int n2 = dp[a] * 2, n3 = dp[b] * 3, n5 = dp[c] * 5;
dp[i] = min(min(n2, n3), n5);
//以下三行的核心思想就是逐步丢弃重复因子的丑数
if(dp[i] == n2) a++;
if(dp[i] == n3) b++;
if(dp[i] == n5) c++;
}
return dp[n - 1];
}
};
Complexity analysis:
Time complexity O(N): where N = n, dynamic programming needs to traverse and calculate the dp list.
Space complexity O(N): A dp list of length N uses O(N) extra space.
Author: jyd
link: https: //leetcode-cn.com/problems/chou-shu-lcof/solution/mian-shi-ti-49-chou-shu-dong-tai-gui-hua-qing-xi-t /
Source: LeetCode (LeetCode)
copyright belongs to the author. For commercial reprints, please contact the author for authorization, and for non-commercial reprints, please indicate the source.