Different C++ Solution


  • 0
    S
    class Solution {
    public:
        vector<vector<int>> permute(vector<int>& nums) {
            unordered_map<int, int> flag;
            for (int i=0; i<nums.size(); i++){
                flag[nums[i]] = 0;
            }
            vector<vector<int>> ans;
            vector<int> item;
            int n = nums.size();
            backtrack(ans, nums, item, flag, n);   
            return ans;
        }
        
        void backtrack(vector<vector<int>> &res, vector<int>& nums, vector<int> item, unordered_map<int, int> &flag, int max){
            if (item.size() == max){
                res.push_back(item);
                return;
            }
            
            for (int i=0; i<max; i++){
                if (flag[nums[i]] == 0){
                    flag[nums[i]] = 1;
                    item.push_back(nums[i]);
                    backtrack(res, nums, item, flag, max);    
                    item.pop_back();
                    flag[nums[i]] = 0;
                }
            }
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.