- class Solution {
- private:
- vector
int>> res; - vector<int> path;
- // vector
used(10); // 私有中vector不支持初始化 - int used[7] = {}; // 私有中静态数组支持初始化
- void backtracking(vector<int>& nums){
- if(path.size() == nums.size()){
- res.push_back(path);
- return;
- }
- for(int i = 0; i < nums.size(); i++){ // 从头开始遍历
- if(used[i] == 1) continue; // 数枝上跳过取过的元素
- used[i] = 1;
- path.push_back(nums[i]);
- backtracking(nums);
- used[i] = 0;
- path.pop_back();
- }
- }
- public:
- vector
int>> permute(vector<int>& nums) { - backtracking(nums);
- return res;
- }
- };
- class Solution {
- private:
- vector
int>> res; - vector<int> path;
- int used[9] = {}; // 私有中静态数组支持初始化
- void backtracking(vector<int>& nums){
- if(path.size() == nums.size()){
- res.push_back(path);
- return;
- }
- for(int i = 0; i < nums.size(); i++){ // 从头开始遍历
- if(used[i] == 1 || i > 0 && used[i - 1] == 0 && nums[i] == nums[i - 1]) continue;
- // 去重,used[i - 1] == 0/1都可以通过,0更好(树层上去重)
- used[i] = 1;
- path.push_back(nums[i]);
- backtracking(nums);
- used[i] = 0;
- path.pop_back();
- }
- }
- public:
- vector
int>> permuteUnique(vector<int>& nums) { - sort(nums.begin(), nums.end()); // 先排序
- backtracking(nums);
- return res;
- }
- };