zoukankan      html  css  js  c++  java
  • 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);
            }
        }
        
    }
  • 相关阅读:
    linux常见的基本操作命令
    CentOS-7安装mongodb
    分布式CAP理论
    Spring-boot2.X整合Apache ActiveMQ5.X
    Apche ActiveMQ5.X介绍及CentOS7的安装
    初识Java消息服务JMS
    初始Apache-Shiro权限认证Web知识点
    Java定时任务总结
    Apache-Shiro自定义Realm实战
    Java 作业题1
  • 原文地址:https://www.cnblogs.com/jasminemzy/p/7849085.html
Copyright © 2011-2022 走看看