Leetcode 46. 全排列

使用next_permutation函数

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

递归做

class Solution {
public:
    vector<int> tt;
    vector<vector<int>> ans;
    int vis[9999] = {};
    void dfs(vector<int>& nums) {
        if (tt.size() == nums.size()) {
            ans.push_back(tt);
            return;
        }
        for (int i = 0; i < nums.size(); ++i)
            if (!vis[i]) tt.push_back(nums[i]), vis[i] = 1, dfs(nums), vis[i] = 0, tt.pop_back();
    }
    vector<vector<int>> permute(vector<int>& nums) {
        for (int i = 0; i < nums.size(); ++i)
            tt.push_back(nums[i]), vis[i] = 1, dfs(nums), vis[i] = 0, tt.pop_back();
        return ans;
    }
};

你可能感兴趣的:(Leetcode 46. 全排列)