• leetcode254- Factor Combinations- 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: 

    1. You may assume that n is always positive.
    2. 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]
    ]
    

      

    算法:DFS。函数头:private void dfs(int target, int num, List<Integer> crt, List<List<Integer>> result) 

    不断拆解为小一点的继续需要整除的数字。从num的数字开始,试着加入能被target整除的那些数字,来递归dfs(target / i, i, crt, result); 最后达到让target变成1的目标。

    细节:用target % i == 0否来判断是否能够整除。

     
    class Solution {
        public List<List<Integer>> getFactors(int n) {
            List<List<Integer>> result = new ArrayList<>();
            if (n <= 1) {
                return result;
            }
            dfs(n, 2, new ArrayList<Integer>(), result);
            return result;
        }
        
        private void dfs(int target, int num, List<Integer> crt, List<List<Integer>> result) {
            
            if (target == 1 && crt.size() > 1) {
                result.add(new ArrayList<Integer>(crt));
                return;
            }
            for (int i = num; i <= target; i++) {
                if (target % i != 0) {
                    continue;
                }
                crt.add(i);
                dfs(target / i, i, crt, result);
                crt.remove(crt.size() - 1);
            }
        }
        
    }
  • 相关阅读:
    mongoDB
    邮箱认证
    Django中开启事务的两种方式
    总结
    __new__和__init__和__call__方法理解
    jupyter
    text()和html()区别
    django模型中auto_now和auto_now_add的区别
    ajax嵌套陷阱
    模板内置函数(HTML)
  • 原文地址:https://www.cnblogs.com/jasminemzy/p/7849085.html
Copyright © 2020-2023  润新知