当前位置:网站首页>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);
}
}
};
边栏推荐
猜你喜欢
ASA归因:如何评估关键词的投放价值
Crawler - basic use of selenium, no interface browser, other uses of selenium, cookies of selenium, crawler cases
leetcode: 212. Word Search II
Cisco - Small Network Topology (DNS, DHCP, Web Server, Wireless Router)
leetcode:255 验证前序遍历序列二叉搜索树
理论篇1:深度学习之----LetNet模型详解
【硬件架构的艺术】学习笔记(1)亚稳态的世界
七夕邂逅爱,那人一定在
物联网应用发展趋势
量化细胞内的信息流:机器学习时代下的研究进展
随机推荐
B. Construct a simple sequence (greedy)
ASA归因:如何评估关键词的投放价值
The Internet of things application development trend
Phasecraft连下两城,助力英国量子技术商业化加速!
Lixia Action | Kyushu Yunzhang Jinnan: Open source is not a movement for a few people, popularization is the source
Makefile syntax and usage notes
Chinese valentine's day, of course, to learn SQL optimization better leave work early to find objects
Makefile 语法及使用笔记
Qt的QItemDelegate使用
CCF GLCC officially opened | Kyushu Cloud open source experts bring generous bonuses to help universities promote open source
js深拷贝和浅拷贝具体使用区别_es6深拷贝和浅拷贝
集合划分差最小问题(01背包)
【Today in History】August 4: First female Turing Award winner; NVIDIA acquires MediaQ; first Cybersecurity Challenge completed
How to Identify Asynchronous I/O Bottlenecks
CloudCompare&PCL 点云按网格划分(点云分幅)
如何确定异步 I/O 瓶颈
Problem solving-->Online OJ (18)
开发者独立搭建一个跨模态搜索应用有多难?
Bluetooth Technology|In the first half of the year, 1.3 million charging piles were added nationwide, and Bluetooth charging piles will become the mainstream of the market
MySQL【窗口函数】【共用表表达式】