J.Gong
2026-11-28
1.73min
Given an array nums of distinct integers, return all its permutations, in any order.
Input: nums = [1,2,3]
Output: [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
Input: nums = [0,1]
Output: [[0,1],[1,0]]
Constraints: , all values are unique, so the answer has exactly arrays.
Solution
This is a backtracking problem. Each time, you pick one item into the array until the array is full, and then you backtrack and choose the next number.
The solution in C# is:
public class Solution {
public IList<IList<int>> Permute(int[] nums) {
var result = new List<IList<int>>();
var path = new List<int>(nums.Length);
var used = new bool[nums.Length];
void BackTrack() {
if (path.Count == nums.Length) {
result.Add(new List<int>(path));
return;
}
for (int i = 0; i < nums.Length; i++) {
if (used[i]) continue;
used[i] = true;
path.Add(nums[i]);
BackTrack();
path.RemoveAt(path.Count - 1);
used[i] = false;
}
}
BackTrack();
return result;
}
}
Note that IList is an interface, so it cannot be instantiated with new.
Many languages have their own implementations of permutation. For example, in Python it is permutations(list[int]):
from itertools import permutations
class Solution:
def permute(self, nums: list[int]) -> list[list[int]]:
return [list(p) for p in permutations(nums)]
In C++:
class Solution {
public:
vector<vector<int>> permute(vector<int>& nums) {
sort(nums.begin(), nums.end());
vector<vector<int>> result;
do {
result.push_back(nums);
} while (next_permutation(nums.begin(), nums.end()));
return result;
}
};
Solving this problem in Go really taught me a lot about arrays and slices in Golang.
The make function has three parameters: type, fill length, and capacity. If the fill length is not provided, the array will be filled with 0s.
[]int(nil) means an empty slice.
func permute(nums []int) [][]int {
var result [][]int
path := make([]int, 0, len(nums))
used := make([]bool, len(nums))
var backtrack func()
backtrack = func() {
if len(path) == len(nums) {
result = append(result, append([]int(nil), path...))
return
}
for i, v := range nums {
if used[i] {
continue
}
used[i] = true
path = append(path, v)
backtrack()
path = path[:len(path)-1]
used[i] = false
}
}
backtrack()
return result
}
For Rust, my solution was terrible, but it can be used to learn smart pointers (I guess).
I used a closure to make the backtrack function; however, it causes a compiler error because anonymous functions cannot call themselves. The way to solve it is to use a struct to wrap the function in a dynamic runtime. Again, it is not a good solution, but I learned a lot.
use std::cell::RefCell;
impl Solution {
pub fn permute(nums: Vec<i32>) -> Vec<Vec<i32>> {
let used = RefCell::new(vec![false; nums.len()]);
let path = RefCell::new(Vec::with_capacity(nums.len()));
let result = RefCell::new(Vec::new());
struct Rec<'a>(&'a dyn Fn(&Rec));
let backtrack = Rec(&|f| {
if path.borrow().len() == nums.len() {
result.borrow_mut().push(path.borrow().clone());
return;
}
for (i, &v) in nums.iter().enumerate() {
if used.borrow()[i] {
continue;
}
used.borrow_mut()[i] = true;
path.borrow_mut().push(v);
(f.0)(f);
path.borrow_mut().pop();
used.borrow_mut()[i] = false;
}
});
(backtrack.0)(&backtrack);
result.into_inner()
}
}