Factor Combinations

8 = 2 x 2 x 2;
8 = 2 x 4.

  • Time: O(n)
  • Space: O(1)
public List<List<Integer>> getFactors(int n) {
    List<List<Integer>> result = new ArrayList<List<Integer>>();
    dfs(result, new ArrayList<Integer>(), n, 2);
    return result;
}

public void dfs(List<List<Integer>> result, 
                List<Integer> item, int n, int start) {
    if (n <= 1) {
        if (item.size() > 1) {
            result.add(new ArrayList<Integer>(item));
        }
        return;
    }
    for (int i = start; i <= n; ++i) {
        if (n % i == 0) {
            item.add(i);
            dfs(result, item, n / i, i);
            item.remove(item.size() - 1);
        }
    }
}

results matching ""

    No results matching ""