LeetCode 254. Factor Combinations
来源:互联网 发布:荣威erx5 知乎 编辑:程序博客网 时间:2024/04/30 04:40
Numbers can be regarded as product of its factors. For example,
8 = 2 x 2 x 2;
= 2 x 4.
Write a function that takes an integer n and return all possible combinations of its factors.
Note:
Each combination’s factors must be sorted ascending, for example: The factors of 2 and 6 is [2, 6], not [6, 2].
You may assume that n is always positive.
Factors should be greater than 1 and less than n.
Examples:
input: 1
output:
[]
input: 37
output:
[]
input: 12
output:
[
[2, 6],
[2, 2, 3],
[3, 4]
]
input: 32
output:
[
[2, 16],
[2, 2, 8],
[2, 2, 2, 4],
[2, 2, 2, 2, 2],
[2, 4, 4],
[4, 8]
]
思路:
1. 枚举所有的情况,用recursive比较合适。例如,32=2*16,把16继续分解!
2. 有一个trick,遍历i从2到i*i<=n,不用费劲做i
vector<vector<int>> getFactors(int n) { vector<vector<int>> res; vector<int> cur; for(int i=2;i*i<=n;i++){ helper(res,cur,i,n); } return res;}void helper(vector<vector<int>>&res,vector<int> cur,int i,int n){ if(n%i) return; int tmp=n/i; cur.push_back(i); cur.push_back(tmp); res.push_back(cur); cur.pop_back(tmp);//语法错误,应该是cur.pop_back();弹出最后一个,没有参数 for(int j=i;j*j<=tmp;j++){ helper(res,cur,j,tmp); }}
0 0
- LeetCode 254. Factor Combinations
- LeetCode 254. Factor Combinations
- [leetcode] 254. Factor Combinations 解题报告
- LeetCode 254. Factor Combinations(因式分解)
- [Leetcode] 254. Factor Combinations 解题报告
- Leetcode Factor Combinations
- 254. Factor Combinations
- 254. Factor Combinations
- LeetCode 题解(253) : Factor Combinations
- [leetcode ] Factor Combinations -------------因数组合
- Factor Combinations
- Factor Combinations
- Factor Combinations
- Factor Combinations
- Leetcode 254. Factor Combinations 找一个数的所有因子(Backtracking)
- [LeetCode254]Factor Combinations
- 254 Factor Combinations
- Medium 254题 Factor Combinations
- file类
- matlab norm 范式
- UbuntuKylin-16.04下安装redis
- 面试前端工程师:Github很重要
- Java SE学习笔记:深入变量、封装思想
- LeetCode 254. Factor Combinations
- 【认证】【比利时】Telenet
- 概率1
- 笔记
- 我遇到的坑
- SpringMVC 引用BootStrap和jQuery
- python学习之Filter
- 表格头拖动、表格内容是否能选中
- Professional English