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:
- You may assume that n is always positive.
- 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的数字是不是>=里面最后一个(如果有的话)。 或者先对factor.sort(),然后每次取得时候从 factors[i:]里面取,这样也可以保证每个解都是递增数列。
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()