当前位置:网站首页>LeetCode刷题--点滴记录023
LeetCode刷题--点滴记录023
2022-07-23 04:16:00 【鲁棒最小二乘支持向量机】
23. 剑指 Offer 49. 丑数
要求
我们把只包含质因子 2、3 和 5 的数称作丑数(Ugly Number)。求按从小到大的顺序的第 n 个丑数。
思路
丑数的递推性质: 丑数只包含因子 2, 3, 5 ,因此有 “丑数 = 某较小丑数 × 某因子”
动态规划:
- 状态定义: 设动态规划列表 dp,dp[i] 代表第 i + 1个丑数
- 转移方程:
当索引 a, b, c 满足以下条件时, dp[i]为三种情况的最小值;
每轮计算 dp[i] 后,需要更新索引 a, b, c 的值,使其始终满足方程条件。实现方法:分别独立判断 dp[i] 和 dp[a]×2 , dp[b]×3 , dp[c]×5 的大小关系,若相等则将对应索引 a , b, c 加 1 - 初始状态: dp[0] = 1 ,即第一个丑数为 1
- 返回值: dp[n-1] ,即返回第 n 个丑数
解题
#include <iostream>
using namespace std;
#include <vector>
class Solution {
public:
int nthUglyNumber(int n) {
int a = 0, b = 0, c = 0;
vector<int> dp(n + 1);
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]; // 返回第 n 个丑数
}
};
void test01()
{
Solution solution;
int n = 10;
cout << solution.nthUglyNumber(n) << endl;
}
int main()
{
test01();
system("pause");
return 0;
}

希望本文对大家有帮助,上文若有不妥之处,欢迎指正
分享决定高度,学习拉开差距
边栏推荐
- 分期付款中的利率问题
- PowerBI入门指南
- Information security is in danger, and it is urgent to control the leakage of enterprise data assets
- 元宇宙浪潮震撼来袭,抓住时机,齐心协力
- IDEA 集成 Sonar 完整流程
- More detailed series than your teacher -- structure
- Is there a fraud in opening an account with Huatai Securities? Is it safe
- 2022/7/20
- UnityC#实现中文汉字转拼音-使用微软CHSPinYinConv库
- How does VirtualBox set up port forwarding?
猜你喜欢

What is the core essence of smart parks?

7.< tag-动态规划和买卖股票合集>lt.121. 买卖股票的最佳时机 + lt.122.买卖股票的最佳时机 II+ lt.123. 买卖股票的最佳时机 III dbc

Kingbasees SQL language reference manual of Jincang database (8. Function (7))

什么是即时通讯?即时通讯的发展

CS5266+MA8621做TYPEC转HDMI+PD+U3+2U+SD/TF七合一拓展坞方案设计|CS5266多口拓展坞PCB+原理图参考

How does VirtualBox set up port forwarding?

How to delete an item in sonar

HoloLens第三视角开发【保姆级教程】【踩坑记录】

Redis transaction - detailed implementation process of seckill case simulation

信息安全危机四伏,企业数据资产泄露管控刻不容缓
随机推荐
UE5 官方案例Lyra全特性详解 6.生成防御塔
大专码农和 985 程序员有什么区别?
腾讯云客户端命令行工具tccli主流程解析
Data warehouse: workflow design and Optimization Practice
performance介绍
Kingbasees SQL language reference manual of Jincang database (8. Function (9))
使用MindStudio的X2MindSpore工具进行训练脚本转换
No routines, no traps, no advertisements | are you sure you don't need this free instant messaging software?
VirtualBox如何设置端口转发?
chrome selenium 用默认profile 不必每次清空
Industry insight | how to better build a data center? It and business should "go together"
中国经济网:“元宇宙”炙手可热
【Delphi】制作控件面板安装图标的简单方法(译)
2022/7/22
Flask learning notes
科技赋能新保险:中华财险的数字化转型
Redis安装
Cache penetration, cache breakdown, cache avalanche
selenium JD爬虫
[vscode] the current working directory is not the current folder /pathlib print CWD path error