Concise 0ms C++ with least params and inline explanation

  • 0
    class Solution {
        vector<vector<int>> getFactors(int n) {
            vector<vector<int>> res;
            helper(n, res, 2);
            return res;
        void helper(int n, vector<vector<int>>& res, int start) {
            // use start to avoid duplicates, e.g. 16
            // avoid adding 4x2x2 because 2x2x4 is already added
            //  i <= n / i is also used to avoid duplicates, e.g. n=6, avoid
            //  adding 3x2 as 2x3 is already added to results
            for (int i = start; i <= n / i; i++) {
                if (n % i) continue;
                // remember end of previous results current i
                // should be only appended to the results of n/i
                int s = res.size();
                helper(n / i, res, i); // recursively get i's factor's result
                for (int j = s; j < res.size(); j++) {
                // append current i and n/i
                res.push_back({i, n/i});

Log in to reply

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