46. Permutations
Asked at 24Amazon57Microsoft55Bloomberg50Google49Apple46Meta43Workday92Infosys54Arista Networks71Booking.com70Microstrategy69Zomato62Qualcomm58LinkedIn57American Express53Samsung53Epic Systems51TikTok50Citadel47tcs42Visa39Uber35Oracle27Goldman Sachs21
Problem
Return every permutation of the distinct integers in nums, in any order.
Example: [1,2,3] → [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
Constraints: n ≤ 6.
Each level picks any unused element (used[] array), depth n = one permutation.
Complexity: O(n · n!).
class Solution:
def permute(self, nums: List[int]) -> List[List[int]]:
res, path, used = [], [], [False] * len(nums)
def bt():
if len(path) == len(nums):
res.append(path[:])
return
for i, x in enumerate(nums):
if not used[i]:
used[i] = True
path.append(x)
bt()
path.pop()
used[i] = False
bt()
return res
assert sorted(Solution().permute([1, 2, 3])) == sorted([[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]])
assert sorted(Solution().permute([0, 1])) == [[0, 1], [1, 0]]
assert Solution().permute([1]) == [[1]]
class Solution {
public List<List<Integer>> permute(int[] nums) {
List<List<Integer>> res = new ArrayList<>();
bt(nums, new boolean[nums.length], new ArrayList<>(), res);
return res;
}
private void bt(int[] nums, boolean[] used, List<Integer> path, List<List<Integer>> res) {
if (path.size() == nums.length) { res.add(new ArrayList<>(path)); return; }
for (int i = 0; i < nums.length; i++) {
if (used[i]) continue;
used[i] = true; path.add(nums[i]);
bt(nums, used, path, res);
used[i] = false; path.remove(path.size() - 1);
}
}
}
func permute(nums []int) [][]int {
res, path, used := [][]int{}, []int{}, make([]bool, len(nums))
var bt func()
bt = func() {
if len(path) == len(nums) {
res = append(res, append([]int{}, path...))
return
}
for i, x := range nums {
if !used[i] {
used[i] = true
path = append(path, x)
bt()
path = path[:len(path)-1]
used[i] = false
}
}
}
bt()
return res
}