My c++ recursive solution


  • 1
    T
    class Solution {
    public:
        vector<vector<int>> getFactors(int n) {
            vector<vector<int>> sols;
            set<vector<int>> solset;
            vector<int> path;
            getFactorRecursive(solset, path, n, 2);
            
            for (set<vector<int>>::iterator it = solset.begin(); it != solset.end(); it++) {
                sols.push_back(*it);
            }
            
            return sols;
        }
        void getFactorRecursive(set<vector<int>>& sols, vector<int>& path, int n, int base) {
            for (int i = base; i <= n/base; i++) {
                if (n%i==0) {
                    path.push_back(i);
                    path.push_back(n/i);
                    sort(path.begin(), path.end());
                    sols.insert(path);
                    path.pop_back();
                    getFactorRecursive(sols, path, n/i, i);
                    path.pop_back();
                }
            }
        }
    };

Log in to reply
 

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