Backtracking in C++


  • 0
    L
    class Solution {
    public:
        vector<vector<int>> getFactors(int n) {
            vector<vector<int>> res;
            vector<int> sol;
            generate(n, 2, sol, res);
            res.pop_back();
            return res;
        }
        
        void generate(int n, int idx, vector<int> &sol, vector<vector<int>> &res) {
            for (int i = idx; i <= n/i; i++) {
                if (n % i)
                    continue;
                sol.push_back(i);
                generate(n/i, i, sol, res);
                sol.pop_back();
            }
            sol.push_back(n);
            res.push_back(sol);
            sol.pop_back();
        }
    };

Log in to reply
 

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