当前位置:网站首页>leetcode:254. 因子的组合
leetcode:254. 因子的组合
2022-08-04 14:31:00 【OceanStar的学习笔记】
题目来源
题目描述

class Solution {
public:
vector<vector<int>> getFactors(int n){
}
};
题目解析
题意
给定一个正整数n,写出所有的因子相乘的形式,而且规定了因子从小到大的顺序排列
思路
- 因为需要列出所有的情况,所以可以用回溯法来解决
- 由于题目中说明了1和n本身不能算其因子,那么可以从2开始遍历到n,如果当前的数i可以被n整除,说明i是n的一个因子,将其存入一位数组 out 中,然后递归调用 n/i,此时不从2开始遍历,而是从i遍历到 n/i
- 停止的条件是当n等于1时,如果此时 out 中有因子,将这个组合存入结果 res 中
class Solution {
public:
vector<vector<int>> getFactors(int n) {
vector<vector<int>> res;
helper(n, 2, {
}, res);
return res;
}
void helper(int n, int start, vector<int> out, vector<vector<int>>& res) {
if (n == 1) {
if (out.size() > 1) res.push_back(out);
return;
}
for (int i = start; i <= n; ++i) {
if (n % i != 0) continue;
out.push_back(i);
helper(n / i, i, out, res);
out.pop_back();
}
}
};

优化
class Solution {
public:
vector<vector<int>> getFactors(int n) {
vector<vector<int>> res;
helper(n, 2, {
}, res);
return res;
}
void helper(int n, int start, vector<int> out, vector<vector<int>> &res) {
for (int i = start; i <= sqrt(n); ++i) {
if (n % i != 0) continue;
vector<int> new_out = out;
new_out.push_back(i);
helper(n / i, i, new_out, res);
new_out.push_back(n / i);
res.push_back(new_out);
}
}
};
边栏推荐
- centos7安装mysql急速版
- 小 P 周刊 Vol.13
- The Internet of things application development trend
- Workaround without Project Facets
- 特殊品种的二次开户验资金额
- C# 动态加载卸载 DLL
- 解题-->在线OJ(十八)
- 【 HMS core 】 【 Media 】 online video editing service 】 【 material can't show, or network anomalies have been Loading state
- 从理论到实践:MySQL性能优化和高可用架构,一次讲清
- 化算力为战力:宁夏中卫的数字化转型启示录
猜你喜欢

基于 Next.js实现在线Excel

token 过期后,如何自动续期?

Cisco-小型网络拓扑(DNS、DHCP、网站服务器、无线路由器)

SLAM 04.视觉里程计-1-相机模型

eNSP-小型网络拓扑(DNS、DHCP、网站服务器、无线路由器)

【Web技术】1401- 图解 Canvas 入门

输入输出流总结

Kyushu Cloud attended the Navigator Online Forum to discuss the current status, challenges and future of 5G MEC edge computing

南瓜科学产品升级 开启益智探索新篇章

zabbix自定义图形
随机推荐
【 HMS core 】 【 Media 】 online video editing service 】 【 material can't show, or network anomalies have been Loading state
特殊品种的二次开户验资金额
第六届未来网络发展大会,即将开幕!
广告电商系统开发功能只订单处理
OAID是什么
16、学习MySQL 正则表达式
【模型部署与业务落地】基于量化芯片的损失分析
基于 Next.js实现在线Excel
快解析结合千方百剂
Unity插件:使用PopulationSystem制作行走交流的路人
Win11快速助手在哪里?Win11打开快速助手的方法
考研上岸又转行软件测试,从5k到13k完美逆袭,杭州校区小哥哥拒绝平庸终圆梦!
Rust from entry to proficient 04-variables
节省50%成本!京东云重磅发布新一代混合CDN产品
快解析结合友加畅捷U+
Workaround without Project Facets
Database recovery
Qt的QItemDelegate使用
蓝牙技术|上半年全国新增 130 万台充电桩,蓝牙充电桩将成为市场主流
谷歌插件.crx文件下载后被自动删除的解决方法