给定一个n,求它的因式分解的所有组合。
从2到sqrt(n)枚举,设当前的值为i,如果i能被n整除,剩下的n//i,一定可以作为当前的组合的最后一个元素,那么第一种组合确定。
以剩下的n//i作为新的n,从i开枚举,枚举到sqrt(n),重复上面的过程。
时间复杂度:O(nlogn)
空间复杂度:O(n)
from typing import (
List,
)
import math
class Solution:
"""
@param n: An integer
@return: a list of combination
we will sort your return value in output
"""
def get_factors(self, n: int) -> List[List[int]]:
# write your code here
ans = []
def dfs(n, f, res):
if res:
res.append(int(n))
ans.append(res[:])
res.pop()
for i in range(f, int(math.sqrt(n))+1):
if n%i == 0:
res.append(int(i))
dfs(n/i, i, res)
res.pop()
dfs(n, 2, [])
return ans