Leetcode Permutations

OpenSoucre發表於2014-07-05

Given a collection of numbers, return all possible permutations.

For example,
[1,2,3] have the following permutations:
[1,2,3][1,3,2][2,1,3][2,3,1][3,1,2], and [3,2,1].

使用遞迴解決

class Solution {
public:
    vector<bool> visit;
    vector<int> num;
    vector<vector<int> > res;
    void dfs(int index , vector<int>& sub){
        if(index == num.size()){
            res.push_back(sub);
            return;
        }
        
        for(int i = 0 ; i < num.size(); ++ i){
            if(!visit[i]){
                visit[i] = true;
                sub[index] = num[i];
                dfs(index+1, sub);
                visit[i] = false;
            }
        }
    }

    vector<vector<int> > permute(vector<int> &num) {
        this->num = num;
        visit.resize(num.size(),false);
        vector<int> sub(num.size(),0);
        dfs(0,sub);
        return res;
    }
};

 

相關文章