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 integernand 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.

input:

32

output:

[
  [2, 16],
  [2, 2, 8],
  [2, 2, 2, 4],
  [2, 2, 2, 2, 2],
  [2, 4, 4],
  [4, 8]
]
import math
class Solution(object):
    def getFactors(self, n):
        """
        :type n: int
        :rtype: List[List[int]]
        """
        retList = []
        if not n:
            return []

        self.solve(n, retList, [], 2)
        return retList
        #return self.solve([], n, [], 2)
    '''
    def solve(self, ret, n, sofar, start):
        if sofar:
            ret.append(sofar + [n])
            #print 'ret: ', ret

        for i in range(start, int(math.sqrt(n))+1):
            if n % i == 0:
                #print 'sofar: ', sofar + [i]
                self.solve(ret, n/i, sofar+[i], i)

        return ret
    '''

    def solve(self, n, retList, curList, start):
        if curList:
            # both of these works
            #retList += [curList[:] +[n]]
            retList += [curList + [n]]
            #print 'retList: ', retList

        for i in xrange(start, int(math.sqrt(n)) + 1):
            if n % i == 0:
                #curList += [i]
                self.solve(n/i, retList, curList + [i], i)
                #curList.pop()

Last updated

Was this helpful?