LeetCode 题解:264. Ugly Number II

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.

解题思路

这道题采用动态规划的解法。
我们可以理解为:每一个丑数都是它前面的某个丑数乘2、乘3或乘5得到的。因此只要前面的丑数按顺序排好就行。每一个丑数都有三种方式得到下一个丑数,那么我们只需要记录某一个丑数第一次得到的方式即可(换句话说它是由它前面的哪个丑数以哪种方式得到的)。在得到新的丑数的同时,要更新能够得到当前丑数的其他丑数的位置,避免重复计算。如此重复,可以得到第n个丑数的大小。

C++代码

class Solution {
public:
    int nthUglyNumber(int n) {
        if(n == 1){
            return 1;
        }
        int index2 = 0, index3 = 0, index5 = 0;
        int rec[1691] = {1};
        int count = 1;
        while(count < n) {
            int p = min(2*rec[index2], min(3*rec[index3], 5*rec[index5]));
            rec[count] = p;
            if(p == 2*rec[index2]) index2++;
            if(p == 3*rec[index3]) index3++;
            if(p == 5*rec[index5]) index5++;
            count++;
        }
        return rec[n-1];
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ZTao-z

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值