当前位置:网站首页>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);
}
}
};
边栏推荐
猜你喜欢

This week to discuss the user experience: Daedalus Nemo to join Ambire, explore the encryption of the ocean

快解析结合千方百剂

idea去掉spark的日志

输入输出流总结

1403. Minimum Subsequence in Non-Increasing Order

Phasecraft连下两城,助力英国量子技术商业化加速!

Hangzhou Electric School Competition (Counter Attack Index)

16、学习MySQL 正则表达式

FRED应用:毛细管电泳系统

Rust 从入门到精通04-变量
随机推荐
leetcode:259. 较小的三数之和
【北亚数据恢复】IBM System Storage存储lvm信息丢失数据恢复方案
爬虫——selenium基本使用、无界面浏览器、selenium的其他用法、selenium的cookie、爬虫案例
16. Learn MySQL Regular Expressions
基于 Next.js实现在线Excel
集合划分差最小问题(01背包)
没有Project Facets的解决方法
metaRTC5.0新版本支持mbedtls(PolarSSL)
Centos7 install mysql version rapidly
Notes for xpath getting node with namespace
B. Construct a simple sequence (greedy)
量化细胞内的信息流:机器学习时代下的研究进展
企业级优化
leetcode: 212. Word Search II
CF1527D MEX Tree (mex & tree & inclusive)
Google plug-in. Download contents file is automatically deleted after solution
Android Sqlite3 basic commands
ASA归因:如何评估关键词的投放价值
技术分享| 小程序实现音视频通话
leetcode:241. 为运算表达式设计优先级