From a6416458ee852961dbaaff9aa9efec51e8350e5b Mon Sep 17 00:00:00 2001 From: Samir Paul <77569653+SamirPaulb@users.noreply.github.com> Date: Wed, 4 Dec 2024 20:07:25 +0530 Subject: [PATCH] Update 22. Factor Combinations.py --- 12_Backtracking/22. Factor Combinations.py | 27 +++++++++++----------- 1 file changed, 13 insertions(+), 14 deletions(-) diff --git a/12_Backtracking/22. Factor Combinations.py b/12_Backtracking/22. Factor Combinations.py index c7f67175..1d5ac6c8 100644 --- a/12_Backtracking/22. Factor Combinations.py +++ b/12_Backtracking/22. Factor Combinations.py @@ -5,21 +5,20 @@ class Solution: def get_factors(self, n: int) -> List[List[int]]: - if n <= 1: - return [] - + self.n = n res = [] - i = 2 - while i*i <= n: - if n%i == 0: - res.append([i, n//i]) - subres = self.get_factors(n//i) - for arr in subres: - if arr[0] >= i: - res.append([i] + arr) - i += 1 - - return res + def solve(n, i, tmp): + if n == 1: + res.append(tmp) + return + while i*i <= n: + if n%i == 0: + solve(n//i, i, tmp + [i]) + i += 1 + if n < self.n: + solve(n//n, n, tmp + [n]) + solve(self.n, 2, []) + return res # Time: O(sqrt(n) * log(n)) # https://algo.monster/liteproblems/254