美文网首页
254. Factor Combinations

254. Factor Combinations

作者: 丁不想被任何狗咬 | 来源:发表于2016-06-17 13:59 被阅读39次
  1. Factor Combinations
    https://leetcode.com/problems/factor-combinations/

我的回溯(220ms):

class Solution {
    void dfs(vector<vector<int>> & res, vector<int> &now, int n, int start) {
        if(n == 1) {
            res.push_back(now);
            return;
        }
        
        for(int i = start; i <= n; i++) {
            if(n % i == 0) {
                now.push_back(i);
                dfs(res, now, n/i, i);
                now.pop_back();
            }
        }
    }
public:
    vector<vector<int>> getFactors(int n) {
        vector<vector<int>> res;
        vector<int> now;
        dfs(res,now,n,2);
        res.pop_back();
        return res;
    }
};

别人的回溯(3ms):

class Solution {
public:
    void getResult(vector<vector<int>> &result,vector<int> &row,int n){
        int i=row.empty()?2:row.back();
        for(;i<=n/i;++i){
            if(n%i==0){
                row.push_back(i);
                row.push_back(n/i);
                result.push_back(row);
                row.pop_back();
                getResult(result,row,n/i);
                row.pop_back();
            }
        }
    }

    vector<vector<int>> getFactors(int n) {
        vector<vector<int>> result;
        vector<int>row;
        getResult(result,row,n);
        return result;
    }
};

284.Peeking Iterator

https://leetcode.com/discuss/59415/simple-solution-line-method-without-extra-member-variables

用复制构造函数
用bool has_next和int next_val

相关文章

网友评论

      本文标题:254. Factor Combinations

      本文链接:https://www.haomeiwen.com/subject/xnxvdttx.html