牛客题霸 [没有重复项数字的所有排列] C++题解/答案

牛客题霸 [没有重复项数字的所有排列] C++题解/答案

题目描述

给出一组数字,返回该组数字的所有排列
例如:
[1,2,3]的所有排列如下
[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2], [3,2,1].
(以数字在数组中的位置靠前为优先级,按字典序排列输出。)

题解:

第一反应就是stl的next_permulatation()
可以实现全排列
如果不用stl可以用dfs实现

代码:

class Solution {
public:
    vector<vector<int> > permute(vector<int> &num) {
        vector<vector<int>>res;
        sort(num.begin(),num.end());
        if(num.empty())return res;
        do
        {
            res.push_back(num);
        }while(next_permutation(num.begin(), num.end()));
        return res;
    }
};
posted @ 2020-12-01 22:30  回归梦想  阅读(234)  评论(0编辑  收藏  举报