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]]
Constraints:
1 <= nums.length <= 610 <= nums[i] <= 10nums are unique.
class Solution {
public:
vector<vector<int>> permute(vector<int>& nums) {
int n = nums.size();
vector<vector<int>> res;
permuteUtil(res,nums,0,n-1);
return res;
}
void permuteUtil(vector<vector<int>> &res,vector<int>& nums,int l,int r)
{
if(l==r)
res.push_back(nums);
else
{
for(int i=l;i<=r;i++)
{
swap(nums[i],nums[l]);
permuteUtil(res,nums,l+1,r);
swap(nums[i],nums[l]);
}
}
}
};
Complexity Analysis:
Time Complexity: O(n*n!) Note that there are n! permutations and it requires O(n) time to print a permutation.