leetcode - Permutations

来源:互联网 发布:ps淘宝 编辑:程序博客网 时间:2024/05/22 01:31

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].

分析:就是在一个集合中N个元素按不同顺序取出其元素组成N!个序列

class Solution {public:    void mute(vector<vector<int> > &v, vector<int> a, int k, vector<int> &num, vector<bool> b)    {        int n = num.size();        if(k == 0)        {            v.push_back(a);            return;        }        for(int i = 0; i < n; i++)        {            if(b[i] == false)            {                a.push_back(num[i]);                b[i] = true;                mute(v,a,k-1,num,b);                b[i] = false;                a.pop_back();            }        }                return;    }    vector<vector<int> > permute(vector<int> &num) {        vector<vector<int> > v;        int n = num.size();        vector<int> a;        vector<bool> IsUsed(n,false);        if(n == 0)return v;        mute(v,a,n,num,IsUsed);        return v;    }};


0 0
原创粉丝点击