permutations

来源:互联网 发布:java服务器插件 编辑:程序博客网 时间:2024/06/01 10:42

题目:

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:    bool next_perm(vector<int>& num) {            int i = num.size()-1, j = num.size()-1;            while(i-1 >= 0 && num[i] < num[i-1])i--;            if(i == 0)                return false;            i--;            while(num[j] < num[i])j--;            std::swap(num[i], num[j]);            reverse(num.begin()+i+1, num.end());            return true;        }    vector<vector<int> > permute(vector<int> &num) {        sort(num.begin(), num.end());        vector<vector<int> > ans;        do {            ans.push_back(num);        }while(next_perm(num));        return ans;    }};

点评:

全排列的非递归实现,STL中的next_permutation 算法实现

原创粉丝点击