Given a collection of distinct integers, return all possible
permutations.Example:code
Input: [1,2,3]
Output: [
[1,2,3],
[1,3,2],
[2,1,3],
[2,3,1],
[3,1,2],
[3,2,1] ]排序
回溯法, 這裏由於每次要從i= 0開始遍歷(若是還繼續用i = index, 就只會有[1,2,3] 而[2,1,1],[3,2,1]的狀況就會錯過)
因此要維護一個列表, 確認每一個數是否被訪問過rem
時間O(n!) 空間O(n)it
class Solution { public List<List<Integer>> permute(int[] nums) { List<List<Integer>> res = new ArrayList<>(); if (nums == null || nums.length == 0) { return res; } List<Integer> tmp = new ArrayList<>(); boolean[] visit = new boolean[nums.length]; dfs(nums, tmp, res, visit); return res; } private void dfs(int[] nums, List<Integer> tmp, List<List<Integer>> res, boolean[] visit) { if (tmp.size() == nums.length) { res.add(new ArrayList<>(tmp)); return; } for (int i =0; i < nums.length; i++) { if (visit[i]) { continue; } tmp.add(nums[i]); visit[i] = true; dfs(nums, tmp, res, visit); tmp.remove(tmp.size() - 1); visit[i] = false; } } }
這裏由於會有重複狀況, 因此要先排序 而後確認當前數和前一個數相同且前一個數沒有被訪問的狀況下跳過.io
時間O(n!) 空間O(n)class
class Solution { public List<List<Integer>> permuteUnique(int[] nums) { List<List<Integer>> res = new ArrayList<>(); if (nums == null || nums.length == 0) { return res; } Arrays.sort(nums); List<Integer> tmp = new ArrayList<>(); boolean[] visit = new boolean[nums.length]; dfs(nums, tmp, res, visit); return res; } private void dfs(int[] nums, List<Integer> tmp, List<List<Integer>> res, boolean[] visit) { if (tmp.size() == nums.length) { res.add(new ArrayList<>(tmp)); return; } for (int i =0; i < nums.length; i++) { if (visit[i]) { continue; } if (i != 0 && nums[i] == nums[i-1] && visit[i-1] == false) { continue; } tmp.add(nums[i]); visit[i] = true; dfs(nums, tmp, res, visit); tmp.remove(tmp.size() - 1); visit[i] = false; } } }