C++ solution using DFS


  • 5
    A
    vector<vector<int>> getFactors(int n) {
        vector<vector<int>> result;
        vector<int> factors;
        dfs(n, 2, factors, result);
        return result;
    }
    
    void dfs(int n, int m, vector<int> &factors, vector<vector<int>> &result) {
        if (n == 1) return;
        
        int k = static_cast<int>(sqrt(n));
        for (int i = m; i <= k; i++) {
            if (n % i == 0) {
                 factors.push_back(i);
                 dfs(n/i, i, factors, result);
                 factors.pop_back();
            }
        }
        
        if (factors.size() > 0) {
            factors.push_back(n);
            result.push_back(factors);
            factors.pop_back();
        }
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.