丑数 Ugly Number
LeetCode传送门264. Ugly Number II
题目
给你一个整数 n ,请你找出并返回第 n 个 丑数 。
丑数 就是只包含质因数 2、3 和/或 5 的正整数。
An ugly number is a positive integer whose prime factors are limited to 2, 3, and 5.
Given an integer n, return the nth ugly number.
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.
Input: n = 1
Output: 1
Explanation: 1 has no prime factors, therefore all of its prime factors are limited to 2, 3, and 5.
Constraints:
1 <= n <= 1690
思考线
解题思路
我们可以用动态规划的方案来解答这道题。
我们设数组dp, 丑数中的第i项就是数组的第i项,则第n个丑数为dp[n-1]
我们初始化条件为最小的丑数1, 所以dp[0] =1;
对于其余的丑数该如何计算,我们定义三个变量a,b,c,表示下一个丑数是当前指针指向的丑数乘以对应的质因数。初始时,三个指针都是0;
然后我们让 dp[i] = Math.min(2*dp[a],3*dp[b],5*dp[c]);然后看dp[i]是否和三个值中的某个值相等,若相等则对应的变量+1;
于是我们就有了一下代码:
function nthUglyNumber(n: number): number {
if(n===1) return n;
// 1,2,3,5
let a = 0, b = 0, c = 0;
const dp = [1];
let i = 1;
while(i<n) {
dp[i] = Math.min(2*dp[a],3*dp[b],5*dp[c]);
if(dp[i] === 2*dp[a]) a++;
if(dp[i] === 3*dp[b]) b++;
if(dp[i] === 5*dp[c]) c++;
i++
}
return dp[n-1];
};
这就是我对本题的解法,如果有疑问或者更好的解答方式,欢迎留言互动。