本问题对应的 leetcode 原文链接:剑指 Offer 49. 丑数
问题描述
我们把只包含质因子 2、3 和 5 的数称作丑数(Ugly Number)。求按从小到大的顺序的第 n 个丑数。
示例 :
输入: n = 10
输出: 12
解释: 1, 2, 3, 4, 5, 6, 8, 9, 10, 12 是前 10 个丑数。
说明:
1
是丑数。n
不超过1690。
解题思路
视频讲解直达: 本题视频讲解
代码实现
class Solution {
public int nthUglyNumber(int n) {
int a = 1, b = 1, c = 1;
int[] dp = new int[n+1];
dp[1] = 1;
for(int i = 2; i <= n; i++){
dp[i] = Math.min(Math.min(dp[a] * 2, dp[b] * 3), dp[c] * 5);
if(dp[i] == dp[a] * 2) a++;
if(dp[i] == dp[b] * 3) b++;
if(dp[i] == dp[c] * 5) c++;
}
return dp[n];
}
}
时间复杂度:O(n)
空间复杂度:O(n)
Python
class Solution(object):
def nthUglyNumber(self, n):
"""
:type n: int
:rtype: int
"""
dp = [0] * (n + 1)
dp[1] = 1
a, b, c = 1, 1, 1
for i in range(2, n + 1):
dp[i] = min(dp[a] * 2, dp[b] * 3, dp[c] * 5)
if dp[i] == dp[a] * 2:
a += 1
if dp[i] == dp[b] * 3:
b += 1
if dp[i] == dp[c] * 5:
c += 1
return dp[n]
C++
class Solution {
public:
int nthUglyNumber(int n) {
vector<int> dp(n+1, 0);
dp[1] = 1;
int a = 1, b = 1, c = 1;
for(int i = 2; i <= n; i++){
dp[i] = min(min(dp[a] * 2, dp[b] * 3), dp[c] * 5);
if(dp[i] == dp[a] * 2) a++;
if(dp[i] == dp[b] * 3) b++;
if(dp[i] == dp[c] * 5) c++;
}
return dp[n];
}
};
Go
func nthUglyNumber(n int) int {
dp := make([]int, n+1)
dp[1] = 1
a, b, c := 1, 1, 1
for i := 2; i <= n; i++ {
dp[i] = min(min(dp[a]*2, dp[b]*3), dp[c]*5)
if dp[i] == dp[a]*2 {
a++
}
if dp[i] == dp[b]*3 {
b++
}
if dp[i] == dp[c]*5 {
c++
}
}
return dp[n]
}
func min(x, y int) int {
if x < y {
return x
}
return y
}
JS
/**
* @param {number} n
* @return {number}
*/
var nthUglyNumber = function(n) {
let a = 1, b = 1, c = 1;
let dp = new Array(n + 1).fill(0);
dp[1] = 1;
for (let i = 2; i <= n; i++) {
dp[i] = Math.min(Math.min(dp[a] * 2, dp[b] * 3), dp[c] * 5);
if (dp[i] == dp[a] * 2) a++;
if (dp[i] == dp[b] * 3) b++;
if (dp[i] == dp[c] * 5) c++;
}
return dp[n];
};