[LeetCode] Permutations

来源:互联网 发布:美橙互联数据库主机名 编辑:程序博客网 时间:2024/06/07 12:10

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<vector<int> > ans;    vector<int> v;    bool *nums;    int len;    vector<vector<int> > permute(vector<int> &num) {        len = num.size();        nums = new bool[len];        for(int i = 0;i < len;i ++)            nums[i] = true;        dfs(num);        return ans;    }    void dfs(vector<int> &num){        if(v.size() == len){            ans.push_back(v);            return;        }        for(int i = 0;i < len;i ++){            if(nums[i]){                v.push_back(num[i]);                nums[i] = false;                dfs(num);                nums[i] = true;                v.pop_back();            }        }    }};


0 0
原创粉丝点击