当前位置:网站首页>leetcode: 254. Combinations of factors
leetcode: 254. Combinations of factors
2022-08-04 14:37:00 【OceanStar study notes】
题目来源
题目描述

class Solution {
public:
vector<vector<int>> getFactors(int n){
}
};
题目解析
题意
给定一个正整数n,Write the form of multiplying all factors,It also specifies that the factors are arranged in order from small to large
思路
- Because of the need to list all the cases,So it can be solved by backtracking
- As stated in the title1和ncannot be counted as a factor by itself,那么可以从2开始遍历到n,如果当前的数i可以被n整除,说明i是n的一个因子,Store it in a one-bit array out 中,然后递归调用 n/i,not at this time2开始遍历,而是从i遍历到 n/i
- The stop condition is whenn等于1时,如果此时 out 中有因子,Store this combination in the result 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);
}
}
};
边栏推荐
猜你喜欢
随机推荐
Cisco - Small Network Topology (DNS, DHCP, Web Server, Wireless Router)
【HMS core】【Media】【视频编辑服务】 在线素材无法展示,一直Loading状态或是网络异常
SQL语句的写法:Update、Case、 Select 一起的用法
《中国综合算力指数》《中国算力白皮书》《中国存力白皮书》《中国运力白皮书》在首届算力大会上重磅发出
Lixia Action | Kyushu Yunzhang Jinnan: Open source is not a movement for a few people, popularization is the source
Workaround without Project Facets
实际工作中的高级技术(训练加速、推理加速、深度学习自适应、对抗神经网络)
leetcode:251. 展开二维向量
vim 常用操作命令
技术分享| 融合调度系统中的电子围栏功能说明
X射线掠入射聚焦反射镜
leetcode: 212. Word Search II
如何确定异步 I/O 瓶颈
OAID是什么
B. Construct a simple sequence (greedy)
FRED应用:毛细管电泳系统
License server system does not support this version of this feature
快解析结合友加畅捷U+
Centos7 install mysql version rapidly
How to fall in love with a programmer








