Permutations

Code:

class Solution {
public:
    int maxDep;
    vector<int> buf; // pack numbers into an array
    vector<vector<int>> res; // pack arrays into an result
    
    void dfs(int dep, vector<bool> &valid, vector<int> &num){
        if(dep==maxDep){
            res.push_back(buf);
            return;
        }
        
        for(int i=0; i<maxDep;i++)
            if(valid[i]){
                valid[i]=false;
                buf.push_back(num[i]);
                dfs(dep+1,valid, num);
                buf.pop_back();
                valid[i]=true;
            }
    }
    
    vector<vector<int> > permute(vector<int> &num) {
        res.clear();
        buf.clear();
        if(num.empty())
            return res;
        vector<bool> valid(num.size(),true);
        maxDep = num.size();
        dfs(0,valid, num);
        return res;
    }
};

 

posted @ 2013-10-26 15:57  WinsCoder  阅读(118)  评论(0编辑  收藏  举报