254. Factor Combinations

254 - Factor Combinations

Total Accepted: 9165 Total Submissions: 25833 Difficulty: Medium

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:
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]
]

Hide Company Tags LinkedIn Uber
Hide Tags Backtracking
Hide Similar Problems (M) Combination Sum

思路

这题和combination sum 比较类似。还是用backtrack方法来做。
factor的范围是 从 [2, 3, 4, ..., n] ,我们用一个变量pos,来记录每次起始factor。然后在backtrack里面递归执行。最后把验证过的factor加入result里面。

public class Solution {
    public List<List<Integer>> getFactors(int n) {
         List<List<Integer>> res = new ArrayList<List<Integer>>();
         if (n < 2) return res;
         backtrack(n, 2, new ArrayList<Integer>(), res);
         return res;
    }
    
    public void backtrack(int n, int pos,  List<Integer> cur, List<List<Integer>> res) {
        if ( n == 1) {
            if (cur.size() > 1 ) {
                res.add(new ArrayList<Integer>(cur));
            }
            
        }
        
        for (int i = pos; i <= n; i++) {
            if (n % i == 0) {
                cur.add(i);
                backtrack(n/i,  i ,cur, res);
                cur.remove(cur.size() - 1); 
            }
           
        }
     }
}
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 13,088评论 0赞 33
  • 忘记了出游的具体日期,但只记得整个路程你的面容最清晰,你有着我喜欢的发型,眉眼,微笑。好像第一个景点的入口开始才注...
    木偶娃娃思绪阅读 244评论 0赞 0
  • 阳光灿烂而又暗藏秘密 是每个午后潮湿阴影里的常态 渴望还是无所求 叶子落地才知道答案 被锁在缝隙里也不懂倾诉 玫瑰...
    落宁阅读 312评论 0赞 3
  • 选择一个男生 看他的眼神 看他的酒品 看他的朋友 看他接爸妈电话的语气 看他花钱的目的 看他对前女友的评价 看他约...
    花猫没有花尾巴阅读 747评论 0赞 0
  • 九月的第二天,早起是做到了,但是早睡还需下很大的决心。今天生意比前段时间都差,然后就一直窝在电脑前逛淘宝,看小说。
    nana0575阅读 308评论 0赞 0

友情链接更多精彩内容