47. Permutations II
来源:互联网 发布:intouch组态软件下载 编辑:程序博客网 时间:2024/05/19 19:14
Given a collection of numbers that might contain duplicates, return all possible unique permutations.
For example,
[1,1,2] have the following unique permutations:
[ [1,1,2], [1,2,1], [2,1,1]]
思路:
还是DFS,不过有重复,那重点就是去重了。同样深度的情况下,出现重复的,那么需要跳过。
具体说就是:判断是否和上一个相等,相等的情况下如果上一个没用过,说明是上一个回溯结束的,同一层,那么就不要再重新来一轮了,跳过。 112 分别以1,1,2开始,第二个1和第一个1开始的结果重复的。在第一个1开始的时候,下一层的当前元素是第二个1,虽然也是1,但是上一个1被用了,说明它是不同深度的,所以不跳过。
class Solution { public List<List<Integer>> permuteUnique(int[] nums) { List<List<Integer>> res = new ArrayList<>(); boolean[] visited = new boolean[nums.length]; Arrays.sort(nums); dfs(res, visited, nums, new ArrayList<>()); return res; } public void dfs(List<List<Integer>> res, boolean[] visited, int[] nums, List<Integer> tempList) { if (tempList.size() == nums.length) { res.add(tempList); } else { for (int i = 0; i < nums.length; i++) { if (i != 0 && nums[i] == nums[i-1] && !visited[i-1]) continue; if (!visited[i]) { visited[i] = true; tempList.add(nums[i]); dfs(res, visited, nums, new ArrayList<>(tempList)); tempList.remove(tempList.size() - 1); visited[i] = false; } } } }}
阅读全文