领英面试原题: 因子组合
LintCode 1308
因子组合
题目描述 数字可以被视为其因数的乘积。例如,8 = 2 x 2 x 2;
= 2 x 4。20
编写一个函数,可以输入整数n并返回其因子的所有可能组合。您可以假设n总是正数。因数应大于1且小于n。
题目描述
8 = 2 x 2 x 2;
= 2 x 4。20
扫码免费做题 ↓↓↓
样例 1
输入: 12
输出:
[
[2, 6],
[ ],
[ ]
]
解释:
2*6 = 12
2*2*3 = 12
3*4 = 12
样例 2
输入: 32
输出:
[
[2, 16],
[ ],
[ ],
[ ],
[ ],
[ ]
]
解释:
2*16=32
2*2*8=32
2*2*2*4=32
2*2*2*2*2=32
2*4*4=32
4*8=32
解题思路
dfs搜索所有的因子组合
源代码
publicclassSolution{
/**
* @param n: a integer
* @return: return a 2D array
*/
publicList<List<Integer>> getFactors(int n) {
// write your code here
List<List<Integer>> result = new ArrayList<List<Integer>>();
helper(result, new ArrayList<Integer>(), n, 2);
return result;
}
public void helper(List<List<Integer>> result, List<Integer> item, int n, int start){
if (n <= 1) {
if (item.size() > 1) {
result.add(new ArrayList<Integer>(item));
}
return;
}
for (int i = start; i <= n; ++i) {
if (n % i == 0) {
item.add(i);
helper(result, item, n/i, i);
item.remove(item.size()-1);
}
}
}
}
查看完整代码,向左滑动
点击【阅读原文】,查看领扣原题。
阅读原文 最新评论
推荐文章
作者最新文章
你可能感兴趣的文章
Copyright Disclaimer: The copyright of contents (including texts, images, videos and audios) posted above belong to the User who shared or the third-party website which the User shared from. If you found your copyright have been infringed, please send a DMCA takedown notice to [email protected]. For more detail of the source, please click on the button "Read Original Post" below. For other communications, please send to [email protected].
版权声明:以上内容为用户推荐收藏至CareerEngine平台,其内容(含文字、图片、视频、音频等)及知识版权均属用户或用户转发自的第三方网站,如涉嫌侵权,请通知[email protected]进行信息删除。如需查看信息来源,请点击“查看原文”。如需洽谈其它事宜,请联系[email protected]。
版权声明:以上内容为用户推荐收藏至CareerEngine平台,其内容(含文字、图片、视频、音频等)及知识版权均属用户或用户转发自的第三方网站,如涉嫌侵权,请通知[email protected]进行信息删除。如需查看信息来源,请点击“查看原文”。如需洽谈其它事宜,请联系[email protected]。