[LeetCode]47 Permutations II
2015-01-02 09:33
1831 查看
https://oj.leetcode.com/problems/permutations-ii/
http://7371901.blog.51cto.com/7361901/1598382
http://www.programcreek.com/2013/02/leetcode-permutations-ii-java/
http://7371901.blog.51cto.com/7361901/1598382
http://www.programcreek.com/2013/02/leetcode-permutations-ii-java/
public class Solution { public List<List<Integer>> permuteUnique(int[] num) { List<List<Integer>> result = new ArrayList<>(); perm(num, 0, result); return result; } //////////////////////// // Solution A: Recursive swap private void perm(int[] n, int start, List<List<Integer>> result) { int len = n.length; if (start >= len) { // A result found. result.add(listof(n)); } for (int i = start ; i < len ; i ++) { // If we have any dups from start to i. // No need to continue recursion // // 注意不要误以为以下两种做法能够去重: // (1)最开始先对数组进行排序,以后每次交换时,只要保证当前要交换的元素和前一个元素不同,这种做法是错误的. // 虽然开始进行了排序,但是元素的交换会使数组再次变的无序 // (2)每次进入递归函数permuteRecur时,对从当前索引开始的子数组排序,这种做法也是错误的. // 因为每次交换元素后,我们要恢复交换的元素,如果在递归函数内排序,就不能正确的恢复交换的元素。 if (unique(n, start, i)) // if (n[start] != n[i]) { swap(n, i, start); perm(n, start + 1, result); swap(n, i, start); } } } private boolean unique(int[] n, int start, int end) { for (int i = start ; i < end ; i ++) { if (n[i] == n[end]) return false; } return true; } private List<Integer> listof(int[] n) { List<Integer> toReturn = new ArrayList<>(n.length); for (int i : n) toReturn.add(i); return toReturn; } private void swap(int[] n, int i , int j) { int t = n[i]; n[i] = n[j]; n[j] = t; } //////////////////////// // Solution B: Insertion + set }
相关文章推荐
- leetcode 47. Permutations II
- LeetCode 47. Permutations II
- LeetCode 47. Permutations II(排列Ⅱ)
- LeetCode47 Permutations II
- LeetCode-47.Permutations II
- LeetCode 47. Permutations II
- leetcode47. Permutations II
- Leetcode 47 Permutations II
- [LeetCode]47 Permutations II
- [leetcode 47] Permutations II
- 【leetcode】【47】Permutations II
- LeetCode-47-Permutations II 递归+dict
- [Leetcode 101] 47 Permutations II
- Leetcode 47. Permutations II
- LeetCode 46 Permutations + LeetCode 47 Permutations II
- LeetCode47:Permutations II
- LeetCode 47. Permutations II
- LeetCode-----46.Permutations&&47.Permutations II (全排列----回溯法)
- LeetCode(47)Permutations II
- [Leetcode] 47. Permutations II