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

Almost all known protein structures in the world are open sourced by DeepMind

量化细胞内的信息流:机器学习时代下的研究进展

【HMS core】【Media】【视频编辑服务】 在线素材无法展示,一直Loading状态或是网络异常

X射线掠入射聚焦反射镜

谷歌插件.crx文件下载后被自动删除的解决方法

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

开发者独立搭建一个跨模态搜索应用有多难?

centos7安装mysql急速版

xampp安装包含的组件有(php,perl,apche,mysql)

leetcode: 253. How many meeting rooms are required at least
随机推荐
idea removes spark logs
Android Sqlite3基本命令
G. Mountaineering Squad (violence & dfs)
vim common operation commands
C# 动态加载卸载 DLL
SQL语句的写法:Update、Case、 Select 一起的用法
ACL 2022 | 社会科学理论驱动的言论建模
Problem solving-->Online OJ (18)
自监督学习未来是掩码自编码器?KAIST最新《自监督学习掩码自编码器》研究进展
G.登山小分队(暴力&dfs)
MySQL【窗口函数】【共用表表达式】
【剑指offer33】二叉搜索树的后序遍历序列
leetcode:212. 单词搜索 II
leetcode: 253. How many meeting rooms are required at least
F.金玉其外矩阵(构造)
AOSP built-in APP franchise rights white list
广告电商系统开发功能只订单处理
数据库恢复
Makefile syntax and usage notes
砺夏行动|九州云章津楠:开源不是少数人的运动,大众化才是源泉