4ms C++ solution


  • 3
    J
    class Solution {
    public:
        vector<vector<int>> getFactors(int n) {
            return getFactors(n, 2);
        }
        vector<vector<int>> getFactors(int n, int k){
            if(n<=0 || k<=0) return {};
            vector<vector<int>> res;
            
            for(int i = k; i<=sqrt(n);i++){
                if(n%i==0) {
                    res.push_back({i, n/i});
                    vector<vector<int>> res2 = getFactors(n/i, i);
                    for(int j =0;j<res2.size();j++){
                        vector<int> temp = res2[j];
                        temp.insert(temp.begin(), i);
                        res.push_back(temp);
                     }
                }
            }
            return res;
        }
    };

  • 0
    S

    Very nice solution. Especially res.push_back({i, n/i}); <= this makes the run much shorter.


Log in to reply
 

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