码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode 254. Factor Combinations

时间:2017-01-05 13:26:23      阅读:162      评论:0      收藏:0      [点我收藏+]

标签:type   example   turn   numbers   mat   should   pre   bsp   examples   

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

标签:type   example   turn   numbers   mat   should   pre   bsp   examples   

原文地址:http://www.cnblogs.com/lettuan/p/6251804.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!