Difficulty:: Medium
Given a collection of distinct integers, return all possible permutations.
Example:
1 2 3 4 5 6 7 8 9 10
| Input: [1,2,3] Output: [ [1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], [3,2,1] ]
|
Solution
Language: Java
简单做法,66%
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| class Solution { public List<List<Integer>> permute(int[] nums) { List<List<Integer>> result = new ArrayList<>(); if (nums == null) { return result; } dfsHelper(nums, result, new ArrayList<Integer>()); return result; } private void dfsHelper(int[] nums, List<List<Integer>> result, List<Integer> p) { if (p.size() == nums.length) { result.add(new ArrayList<Integer>(p)); return; } for (int i = 0; i < nums.length; i++) { if (p.contains(nums[i])) { continue; } p.add(nums[i]); dfsHelper(nums, result, p); p.remove(p.size() - 1); } } }
|
记忆化搜索 100%
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
| class Solution { public List<List<Integer>> permute(int[] nums) { List<List<Integer>> result = new ArrayList<>(); if (nums == null) { return result; } boolean[] visited = new boolean[nums.length]; dfsHelper(nums, result, new ArrayList<Integer>(), visited); return result; } private void dfsHelper(int[] nums, List<List<Integer>> result, List<Integer> p, boolean[] visited) { if (p.size() == nums.length) { result.add(new ArrayList<Integer>(p)); return; } for (int i = 0; i < nums.length; i++) { if (visited[i]) { continue; } p.add(nums[i]); visited[i] = true; dfsHelper(nums, result, p, visited); visited[i] = false; p.remove(p.size() - 1); } } }
|