46. Permutations

Question

LeetCode Problem

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:


Solutions

bool nextPermutation(vector<int>& nums) {
	int n = static_cast<int>(nums.size());
	int i = n - 2;
	while (i >= 0 && nums[i] >= nums[i+1]) {
		i--;
	}
	if (i < 0) return false;
	int j = n - 1;
	while (nums[i] < nums[j]) {
		j--;
	}
	swap(nums[i], nums[j]);
	reverse(nums.begin() + i + 1, nums.end());
	return true;
}

vector<vector<int>> permute(vector<int>& nums) {
	// use C++ STL permutation function to enumate all
    // permutation. first need to sort the nums first in case 
    // missing previous permutations.
    // Time Complexity: O(NLogN) for sorting and O(N * N!) for the enumerate all permutations.
    // Space Complexity: O(1) excluded from the output.
	sort(nums.begin(), nums.end());
	vector<vector<int>> result;
	do {
		result.push_back(nums);
	} while (nextPermutation());
	return result;
}