LeetCode Factor Combinations

本文介绍了如何使用回溯算法解决整数分解组合问题,包括了算法实现细节、时间复杂度分析及代码实现,通过实例展示了如何在给定整数 n 的情况下找出所有可能的分解组合。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

原题链接在这里:https://leetcode.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.

Note: 

  1. Each combination's factors must be sorted ascending, for example: The factors of 2 and 6 is [2, 6], not [6, 2].
  2. You may assume that n is always positive.
  3. 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]
]

题解:

Combination Sum 都是backtracking 的题目. factor 从2 开始,若是target能除以factor, 就把factor加到item中,继续用target/factor做新的target找.

Base case 是target变成了1, 并且item的size要大于1. 这里对item 的size 有要求是因为若初始target = 12, 返回结果是不应该包含{12}这个item的。

Time Complexity: Exponential. Space: log(target).

AC Java:

 1 public class Solution {
 2     public List<List<Integer>> getFactors(int n) {
 3         List<List<Integer>> res = new ArrayList<List<Integer>>();
 4         if(n<=1){
 5             return res;
 6         }
 7         
 8         findFactors(n, 2, new ArrayList<Integer>(), res);
 9         return res;
10     }
11     
12     //注意要写好的signature
13     private void findFactors(int n, int factor, List<Integer> item, List<List<Integer>> res){
14         //base case 不但要n==1, 还需要item.size() > 1, 否则n = 2, 就会添加一个item {2}.
15         if(n == 1 && item.size() > 1){
16             res.add(new ArrayList<Integer>(item));
17             return;
18         }
19         for(int i = factor; i<=n; i++){
20             if(n%i == 0){
21                 item.add(i);
22                 findFactors(n/i, i, item, res);
23                 item.remove(item.size()-1);
24             }
25         }
26     }
27 }

 

转载于:https://www.cnblogs.com/Dylan-Java-NYC/p/5219299.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值