Skip to content

254. Factor Combinations 👍

  • Time: $O(n\log n)$
  • Space: $O(\log n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
 public:
  vector<vector<int>> getFactors(int n) {
    vector<vector<int>> ans;
    dfs(n, 2, {}, ans);  // The minimum factor is 2.
    return ans;
  }

 private:
  void dfs(int n, int s, vector<int>&& path, vector<vector<int>>& ans) {
    if (n <= 1) {
      if (path.size() > 1)
        ans.push_back(path);
      return;
    }

    for (int i = s; i <= n; ++i)
      if (n % i == 0) {
        path.push_back(i);
        dfs(n / i, i, std::move(path), ans);
        path.pop_back();
      }
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
  public List<List<Integer>> getFactors(int n) {
    List<List<Integer>> ans = new ArrayList<>();
    dfs(n, 2, new ArrayList<>(), ans); // The minimum factor is 2.
    return ans;
  }

  private void dfs(int n, int s, List<Integer> path, List<List<Integer>> ans) {
    if (n == 1) {
      if (path.size() > 1)
        ans.add(new ArrayList<>(path));
      return;
    }

    for (int i = s; i <= n; ++i)
      if (n % i == 0) {
        path.add(i);
        dfs(n / i, i, path, ans);
        path.remove(path.size() - 1);
      }
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
class Solution:
  def getFactors(self, n: int) -> list[list[int]]:
    ans = []

    def dfs(n: int, s: int, path: list[int]) -> None:
      if n <= 1:
        if len(path) > 1:
          ans.append(path.copy())
        return

      for i in range(s, n + 1):
        if n % i == 0:
          path.append(i)
          dfs(n // i, i, path)
          path.pop()

    dfs(n, 2, [])  # The minimum factor is 2.
    return ans