46 - Permutations & 47 - Permutations II

46 - Permutations

#medium

Given an array nums of distinct integers, return all the possible permutations. You can return the answer in any order.

Example 1:
Input: nums = [1,2,3]
Output: [ [1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1] ]

Example 2:
Input: nums = [0,1]
Output: [ [0,1],[1,0] ]

Example 3:
Input: nums = [1]
Output: [ [1] ]

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

    void backtracking( vector<int> nums, vector<bool> used ) {
        if ( path.size() == nums.size() ) {
            result.push_back( path );
            return;
        }

        for ( int i = 0; i < nums.size(); i++ ) {
            if ( used[i] ) continue;
            path.push_back( nums[i] );
            used[i] = true;
            backtracking( nums, used );
            used[i] = false;
            path.pop_back();
        }

    }

    vector<vector<int>> permute(vector<int>& nums) {
        vector<bool> used( nums.size(), false );
        backtracking( nums, used );
        return result;    
    }
};

47 - Permutations II