Question Given an array nums
of distinct integers, return all the possible permutations . You can return the answer in any order .
https://leetcode.com/problems/permutations/
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 public List<List<Integer>> permute(int [] nums) { List<List<Integer>> res = new ArrayList<>(); backtrack(res, new ArrayList<>(), nums); return res; } private void backtrack (List<List<Integer>> list, List<Integer> tempList, int [] nums) { if (tempList.size() == nums.length){ list.add(new ArrayList<>(tempList)); } else { for (int i = 0 ; i < nums.length; i++){ if (tempList.contains(nums[i])) continue ; tempList.add(nums[i]); backtrack(list, tempList, nums); tempList.remove(tempList.size() - 1 ); } } }
Complexity:
Time complexity: O(N!)
Space complexity: O(n)