首页 文章详情

​LeetCode刷题实战254:因子的组合

程序IT圈 | 452 2021-05-05 06:59 0 0 0
UniSMS (合一短信)
算法的重要性,我就不多说了吧,想去大厂,就必须要经过基础知识和业务逻辑面试+算法面试。所以,为了提高大家的算法能力,这个公众号后续每天带大家做一道算法题,题目就从LeetCode上面选 !

今天和大家聊的问题叫做 因子的组合,我们先来看题面:
https://leetcode-cn.com/problems/factor-combinations/

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.

请实现一个函数,该函数接收一个整数 n 并返回该整数所有的因子组合。

示例


注意:
你可以假定 n 为永远为正数。
因子必须大于 1 并且小于 n

示例 1
输入: 1
输出: []

示例 2
输入: 37
输出: []

示例 3
输入: 12
输出:
[
  [2, 6]
,
  [2, 2, 3],
  [3, 4]
]

示例 4:
输入: 32
输出:
[
  [2, 16]
,
  [2, 2, 8],
  [2, 2, 2, 4],
  [2, 2, 2, 2, 2],
  [2, 4, 4],
  [4, 8]
]



解题


可以采用递归。从2开始遍历到sqrt(n),能被n整除就进下一个递归,当start超过sqrt(n)时,start变成n,进下一个递归。

public class Solution {
    public List<List<Integer>> getFactors(int n) {
        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 * i <= n; ++i) {
            if (n % i == 0) {
                item.add(i);
                helper(result, item, n/i, i);
                item.remove(item.size()-1);
            }
        }
        
        int i = n;
        item.add(i);
        helper(result, item, 1, i);
        item.remove(item.size()-1);
    }
}


好了,今天的文章就到这里,如果觉得有所收获,请顺手点个在看或者转发吧,你们的支持是我最大的动力 。

上期推文:

LeetCode1-240题汇总,希望对你有点帮助!

LeetCode刷题实战241:为运算表达式设计优先级

LeetCode刷题实战242:有效的字母异位词

LeetCode刷题实战243:最短单词距离

LeetCode刷题实战244:最短单词距离 II

LeetCode刷题实战245:最短单词距离 III

LeetCode刷题实战246:中心对称数

LeetCode刷题实战247:中心对称数II

LeetCode刷题实战248:中心对称数III

LeetCode刷题实战249:移位字符串分组

LeetCode刷题实战250:统计同值子树

LeetCode刷题实战251:展开二维向量

LeetCode刷题实战252:会议室

LeetCode刷题实战253:会议室II


good-icon 0
favorite-icon 0
收藏
回复数量: 0
    暂无评论~~
    Ctrl+Enter