Permutations Leetcode
Given a collection of distinct numbers, return all possible permutations.
For example,[1,2,3]
have the following permutations:
[ [1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], [3,2,1] ]
Show Similar Problems
其实这道题和前面的一样。。。只需要判断存在就跳过就可以了。。。。。。。。。。。。。。。然而。。。。。都是泪。。。。。。
public class Solution { List<List<Integer>> result; List<Integer> current; public List<List<Integer>> permute(int[] nums) { result = new ArrayList<>(); if (nums == null || nums.length == 0) { return result; } current = new ArrayList<>(); helper(nums, 0); return result; } public void helper(int[] nums, int control) { if (control >= nums.length) { result.add(new ArrayList<>(current)); } for (int i = 0; i < nums.length; i++) { if (current.contains(nums[i])) { continue; } current.add(nums[i]); helper(nums, control + 1); current.remove(current.size() - 1); } } }
这道题还有非递归的方法,挺巧妙的。而且比递归的方法要快。
The idea is that first choose one element, and insert the second element to different places.
[1] -> [1, 2], [2, 1] -> [3, 1, 2], [1, 3, 2], [1, 2, 3], [3, 2, 1], [2, 3, 1], [2, 1, 3]
需要注意的是,每次get的时候其实不能get第k个因为remove长度已经变了,只要get第0个就可以了。
public class Solution { List<List<Integer>> result; List<Integer> current; public List<List<Integer>> permute(int[] nums) { result = new ArrayList<>(); if (nums == null || nums.length == 0) { return result; } current = new ArrayList<>(); current.add(nums[0]); result.add(current); for (int i = 1; i < nums.length; i++) { int bigSize = result.size(); for(int k = 0; k < bigSize; k++) { List<Integer> l = result.get(0); int size = l.size(); for (int j = 0; j <= size; j++) { List<Integer> tmp = new ArrayList<>(l); tmp.add(j, nums[i]); result.add(tmp); } result.remove(l); } } return result; } }
也可以用新建list来代替用size控制,快了1ms
public class Solution { List<List<Integer>> result; List<Integer> current; public List<List<Integer>> permute(int[] nums) { result = new ArrayList<>(); if (nums == null || nums.length == 0) { return result; } current = new ArrayList<>(); current.add(nums[0]); result.add(current); for (int i = 1; i < nums.length; i++) { List<List<Integer>> newResult = new ArrayList<>(); for(int k = 0; k < result.size(); k++) { List<Integer> l = result.get(k); int size = l.size(); for (int j = 0; j <= size; j++) { List<Integer> tmp = new ArrayList<>(l); tmp.add(j, nums[i]); newResult.add(tmp); } } result = newResult; } return result; } }