Posted on

Description

Submission

class Solution {
public:
    vector<vector<int>> permute(vector<int>& nums) {
        vector<bool> used(nums.size(), false);
        vector<vector<int>> res;
        backtrack(used, nums, res, {}, 0);
        return res;
    }
private:
    void backtrack(vector<bool>& used, vector<int>& nums, vector<vector<int>>& res, vector<int> hand, int used_count)
    {
        if(used_count == nums.size()) {
            res.push_back(hand);
            return;
        }

        for(int i = 0; i < nums.size(); ++i) {
            if(!used[i]) {
                vector<int> new_hand {hand.begin(), hand.end()};
                new_hand.push_back(nums[i]);
                used[i] = true;
                backtrack(used, nums, res, new_hand, used_count + 1);
                used[i] = false;
            }
        }
    }
    
};

Another Submission

The new hand is not necessary, using pop_back() method of vector.

class Solution {
public:
    vector<vector<int>> permute(vector<int>& nums) {
        vector<bool> used(nums.size(), false);
        vector<vector<int>> res;
        backtrack(used, nums, res, {}, 0);
        return res;
    }
private:
    void backtrack(vector<bool>& used, vector<int>& nums, vector<vector<int>>& res, vector<int> hand, int used_count)
{
    if(used_count == nums.size()) {
        res.push_back(hand);
        return;
    }

    for(int i = 0; i < nums.size(); ++i) {
        if(!used[i]) {
            hand.push_back(nums[i]);
            used[i] = true;
            backtrack(used, nums, res, hand, used_count + 1);
            hand.pop_back();
            used[i] = false;
        }
    }
}
    
};

Leave a Reply

Your email address will not be published. Required fields are marked *