full array

If no repeating elements are included, then all permutations can be printed as follows

#include<bits/stdc++.h>

class Solution {
public:
    void dfs(vector<int>vec, int cur, vector<vector<int>>&ans){
        if (cur == vec.size()-1){
            ans.push_back(vec);
            return;
        }
        for(int i = cur; i < vec.size(); ++i){
            //if(i != cur and vec[i] == vec[cur]) continue;
            swap(vec[i], vec[cur]);
            dfs(vec, cur + 1, ans);
        }
    }

    vector<vector<int>> permute(vector<int>& nums) {
        vector<vector<int>>ans;
        //sort(nums.begin(), nums.end());
        dfs(nums, 0, ans);
        return ans;
    }
};

If it contains heavy elements, it needs to be sorted first, and then the interval where the repeated elements are located is regarded as one.

#include<bits/stdc++.h>

class Solution {
public:
    void dfs(vector<int>vec, int cur, vector<vector<int>>&ans){
        if (cur == vec.size()-1){
            ans.push_back(vec);
            return;
        }
        for(int i = cur; i < vec.size(); ++i){
            if(i != cur and vec[i] == vec[cur]) continue;
            swap(vec[i], vec[cur]);
            dfs(vec, cur + 1, ans);
        }
    }

    vector<vector<int>> permuteUnique(vector<int>& nums) {
        vector<vector<int>>ans;
        sort(nums.begin(), nums.end());
        dfs(nums, 0, ans);
        return ans;
    }
};

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325167189&siteId=291194637