leetcode46全排列C++

1、题目

https://leetcode-cn.com/problems/permutations/

2、题意

题解1:STL next_permution 这个函数是从当前序列开始逐步排列出字典序更大的组合,所以如果想得到全排列的话需要先把序列排序一下,否则枚举不全

class Solution {
     
public:
    vector<vector<int>> permute(vector<int>& nums) {
     
        sort(nums.begin(),nums.end());
        vector<vector<int>> res;
        do{
     
            res.push_back(nums);
        }while(next_permutation(nums.begin(),nums.end()));
        return res;
    }
};

题解2:回溯dfs

class Solution {
     
public:
    vector<vector<int>> res;
    void dfs(vector<bool>&st,vector<int>&temp,vector<int>&nums)
    {
     
        if(st.size()==temp.size())
        {
     
            res.push_back(temp);
            return;
        }
        else{
     
            for(int i=0;i<nums.size();i++)
            {
     
                if(!st[i])
                {
     
                    st[i] = true;
                    temp.push_back(nums[i]);
                    dfs(st,temp,nums);
                    st[i] = false;
                    temp.pop_back();
                }
            }
        }
    }
    vector<vector<int>> permute(vector<int>& nums) {
     
        vector<bool> st(nums.size(),false);
        vector<int> temp;
        if(nums.size()==0)
            return {
     };
        else if(nums.size()==1)
            return {
     {
     nums[0]}};
        else
            dfs(st,tempclass Solution {
     
public:
    vector<vector<int>> res;
    vector<int> temp;
    void dfs(vector<bool>&st,vector<int>& nums)
    {
     
        if(nums.size()==temp.size())
        {
     
            res.push_back(temp);
            return;
        }
        for(int i=0;i<nums.size();i++)
        {
     
            if(!st[i])
            {
     
                st[i] = true;
                temp.push_back(nums[i]);
                dfs(st,nums);
                temp.pop_back();
                st[i] = false;
            }
        }
    }
    vector<vector<int>> permute(vector<int>& nums) {
     
        vector<bool> st(nums.size(),false);
        if(nums.size()==0)
            return {
     };
        else if(nums.size()==1)
            return {
     {
     nums[0]}};
        dfs(st,nums);
        return res;
    }
};,nums);
        return res;
    }
};

解法3:交换法 交换法得到的序列并不是从小到大的

class Solution {
     
public:
    vector<vector<int>> res;
    void dfs(vector<int>& nums,int start)
    {
     
        if(start==nums.size()-1)
            {
     res.push_back(nums);
            return;
            }
        for(int i=start;i<nums.size();i++)
        {
     
            swap(nums[i],nums[start]);
            dfs(nums,start+1);
            swap(nums[start],nums[i]);
        }
    }
    vector<vector<int>> permute(vector<int>& nums) {
     
        if(nums.size()==0)
            return {
     };
        else if(nums.size()==1)
            return {
     {
     nums[0]}};
        dfs(nums,0);
        return res;
    }
};

你可能感兴趣的:(leetcode,leetcode)