C++:
class Solution {
public:
void backtrack(vector<vector<int>>& results, vector<int>& nums, int first, int length) {
if ( first == length ) {
results.push_back( nums );
return;
}
for ( int i = first; i < length; ++i ) {
std::swap( nums[i], nums[first] );
backtrack( results, nums, first + 1, length );
std::swap( nums[i], nums[first] );
}
}
vector<vector<int>> permute(vector<int>& nums) {
std::vector<std::vector<int>> results;
backtrack( results, nums, 0, (int)nums.size() );
return results;
}
};