You are given an array of distinct integers, nums
. Return all possible permutations of the elements in nums
.
Example:
Input: nums = [1,2,3]
Output: [
[1,2,3],
[1,3,2],
[2,1,3],
[2,3,1],
[3,1,2],
[3,2,1]
]
Constraints:
1 <= nums.length <= 6
-10 <= nums[i] <= 10
nums
are unique.Q: Can the input array contain duplicated elements? A: No, the array of integers is distinct as per the problem statement.
Q: What should we return if the input array is empty?
A: According to the constraint 1 <= nums.length
, we can assume the array won’t be empty.
#include <vector>
class Solution {
public:
void backtrack(std::vector<int>& nums, std::vector<bool>& visited, std::vector<int>& current, std::vector<std::vector<int>>& result) {
if (current.size() == nums.size()) {
result.push_back(current);
return;
}
for (int i = 0; i < nums.size(); ++i) {
if (!visited[i]) {
visited[i] = true;
current.push_back(nums[i]);
backtrack(nums, visited, current, result);
current.pop_back();
visited[i] = false;
}
}
}
std::vector<std::vector<int>> permute(std::vector<int>& nums) {
std::vector<std::vector<int>> result;
std::vector<int> current;
std::vector<bool> visited(nums.size(), false);
backtrack(nums, visited, current, result);
return result;
}
};
n
elements is n!
.O(n)
time to copy it to the result list.O(n * n!)
.O(n * n!)
for storing all the permutations.O(n)
extra space.Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?