【力扣】排列問題(回溯法)(去重)

SaTsuki26681534發表於2024-03-09

題目描述

image

class Solution {
public:
vector<vector<int>> res;
vector<int> path;

void backtrace(vector<int>& nums, int used[]){
    if(path.size() == nums.size()){
        res.push_back(path);
        return ;
    }

    for(int i = 0; i < nums.size(); i++){
        if(used[i] ){
            continue;
        }
	//這裡
        if(i!=0 && nums[i] == nums[i-1] && !used[i-1]){
            continue;
        }
        path.push_back(nums[i]);
        used[i] = 1;
        backtrace(nums, used);
        path.pop_back();
        used[i] = 0;
    }
}
    vector<vector<int>> permuteUnique(vector<int>& nums) {
        res.clear();
        path.clear();
        sort(nums.begin(), nums.end());
        int n = nums.size();
        int *used = new int[n];
        memset(used, 0, sizeof(int)*n);
        backtrace(nums,used);
        return res;
    }
};

相關文章