Leetcode 254. Factor Combinations

Posted lettuan

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leetcode 254. 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. 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]
]

解法一:

先求出所有的factor,在用DFS。注意由于答案中的factor都是升序排列,所以在往line里加入数字时先判断一下要加入line的数字是不是>=里面最后一个(如果有的话)。

 1 class Solution(object):
 2     def getFactors(self, n):
 3         """
 4         :type n: int
 5         :rtype: List[List[int]]
 6         """
 7         res = []
 8         line = []
 9         factors = []
10         for i in range(2,int(math.sqrt(n))+1):
11             if n%i == 0 and i< math.sqrt(n):
12                 factors.append(i)
13                 factors.append(n/i)
14             elif n == i*i:
15                 factors.append(i)
16         if not factors:
17             return []
18         self.DFS(factors, n, res, line)
19         return res
20     
21     
22     def DFS(self, nums, target, res, line):
23         if target == 1:
24             res.append([x for x in line])
25             return 
26         
27         if target > 1:
28             for elem in nums:
29                 if target % elem == 0 and (not line or line and elem >= line[-1]):
30                     line.append(elem)
31                     self.DFS(nums, target/elem, res, line)
32                     line.pop()

 








以上是关于Leetcode 254. Factor Combinations的主要内容,如果未能解决你的问题,请参考以下文章

254.Factor Combinations

254. Factor Combinations

254. Factor Combinations

254 Factor Combinations

[LC] 254. Factor Combinations

[LeetCode] Factor Combinations 因子组合