Factor Combinations

medium backtracking math

Problem

Numbers can be regarded as the product of their factors. Return all unique combinations of factors of n (each factor ≥ 2 and the combination excludes n itself).

Inputn = 12
Output[[2,6],[2,2,3],[3,4]]
12 = 2·6 = 2·2·3 = 3·4 (4·3 is the same combo and gets pruned by the ascending-start rule).

def get_factors(n):
    res = []
    def back(start, remain, path):
        i = start
        while i * i <= remain:
            if remain % i == 0:
                res.append(path + [i, remain // i])
                back(i, remain // i, path + [i])
            i += 1
    back(2, n, [])
    return res
function getFactors(n) {
  const res = [];
  function back(start, remain, path) {
    for (let i = start; i * i <= remain; i++) {
      if (remain % i === 0) {
        res.push([...path, i, remain / i]);
        back(i, remain / i, [...path, i]);
      }
    }
  }
  back(2, n, []);
  return res;
}
class Solution {
    List> res = new ArrayList<>();
    public List> getFactors(int n) {
        back(2, n, new ArrayList<>()); return res;
    }
    void back(int start, int remain, List path) {
        for (int i = start; i * i <= remain; i++) {
            if (remain % i == 0) {
                List c = new ArrayList<>(path); c.add(i); c.add(remain / i);
                res.add(c);
                path.add(i); back(i, remain / i, path); path.remove(path.size() - 1);
            }
        }
    }
}
class Solution {
    vector> res;
    void back(int start, int remain, vector& path) {
        for (int i = start; i * i <= remain; i++) {
            if (remain % i == 0) {
                auto c = path; c.push_back(i); c.push_back(remain / i);
                res.push_back(c);
                path.push_back(i); back(i, remain / i, path); path.pop_back();
            }
        }
    }
public:
    vector> getFactors(int n) { vector p; back(2, n, p); return res; }
};
Time: O(n^{log log n}) (output-sensitive) Space: O(log n) recursion