# Permutations II
### Source
- leetcode: [Permutations II | LeetCode OJ](https://leetcode.com/problems/permutations-ii/)
- lintcode: [(16) Permutations II](http://www.lintcode.com/en/problem/permutations-ii/)
### Problem
Given a list of numbers with duplicate number in it. Find all **unique** permutations.
#### Example
For numbers `[1,2,2]` the unique permutations are:
~~~
[
[1,2,2],
[2,1,2],
[2,2,1]
]
~~~
#### Challenge
Do it without recursion.
### 题解1 - backtracking
在上题的基础上进行剪枝,剪枝的过程和 [Unique Subsets](http://algorithm.yuanbin.me/zh-cn/exhaustive_search/unique_subsets.html) 一题极为相似。为了便于分析,我们可以先分析简单的例子,以 [1,21,22][1, 2_1, 2_2][1,21,22] 为例。按照上题 Permutations 的解法,我们可以得到如下全排列。
1. [1,21,22][1, 2_1, 2_2][1,21,22]
1. [1,22,21][1, 2_2, 2_1][1,22,21]
1. [21,1,22][2_1, 1, 2_2][21,1,22]
1. [21,22,1][2_1, 2_2, 1][21,22,1]
1. [22,1,21][2_2, 1, 2_1][22,1,21]
1. [22,21,1][2_2, 2_1, 1][22,21,1]
从以上结果我们注意到`1`和`2`重复,`5`和`3`重复,`6`和`4`重复,从重复的解我们可以发现其共同特征均是第二个 222_222 在前,而第一个 212_121 在后,因此我们的**剪枝方法为:对于有相同的元素来说,我们只取不重复的一次。**嗯,这样说还是有点模糊,下面以 [1,21,22][1, 2_1, 2_2][1,21,22] 和 [1,22,21][1, 2_2, 2_1][1,22,21] 进行说明。
首先可以确定 [1,21,22][1, 2_1, 2_2][1,21,22] 是我们要的一个解,此时`list`为 [1,21,22][1, 2_1, 2_2][1,21,22], 经过两次`list.pop_back()`之后,`list`为 [1][1][1], 如果不进行剪枝,那么接下来要加入`list`的将为 222_222, 那么我们剪枝要做的就是避免将 222_222 加入到`list`中,如何才能做到这一点呢?我们仍然从上述例子出发进行分析,在第一次加入 222_222 时,相对应的`visited[1]`为`true`(对应 212_121),而在第二次加入 222_222 时,相对应的`visited[1]`为`false`,因为在`list`为 [1,21][1, 2_1][1,21] 时,执行`list.pop_back()`后即置为`false`。
一句话总结即为:在遇到当前元素和前一个元素相等时,如果前一个元素`visited[i - 1] == false`, 那么我们就跳过当前元素并进入下一次循环,这就是剪枝的关键所在。另一点需要特别注意的是这种剪枝的方法能使用的前提是提供的`nums`是有序数组,否则无效。
### C++
~~~
class Solution {
public:
/**
* @param nums: A list of integers.
* @return: A list of unique permutations.
*/
vector<vector<int> > permuteUnique(vector<int> &nums) {
vector<vector<int> > ret;
if (nums.empty()) {
return ret;
}
// important! sort before call `backTrack`
sort(nums.begin(), nums.end());
vector<bool> visited(nums.size(), false);
vector<int> list;
backTrack(ret, list, visited, nums);
return ret;
}
private:
void backTrack(vector<vector<int> > &result, vector<int> &list, \
vector<bool> &visited, vector<int> &nums) {
if (list.size() == nums.size()) {
result.push_back(list);
// avoid unnecessary call for `for loop`, but not essential
return;
}
for (int i = 0; i != nums.size(); ++i) {
if (visited[i] || (i != 0 && nums[i] == nums[i - 1] \
&& !visited[i - 1])) {
continue;
}
visited[i] = true;
list.push_back(nums[i]);
backTrack(result, list, visited, nums);
list.pop_back();
visited[i] = false;
}
}
};
~~~
### 源码分析
Unique Subsets 和 Unique Permutations 的源码模板非常经典!建议仔细研读并体会其中奥义。
后记:在理解 Unique Subsets 和 Unique Permutations 的模板我花了差不多一整天时间才基本理解透彻,建议在想不清楚某些问题时先分析简单的问题,在纸上一步一步分析直至理解完全。
### 题解2 - 字典序
Permutation 的题使用字典序的做法其实更为简单,且为迭代的解法,效率也更高。代码和之前的 Permutations 那道题一模一样。
### Java
~~~
public class Solution {
public List<List<Integer>> permuteUnique(int[] nums) {
List<List<Integer>> result = new ArrayList<List<Integer>>();
if (nums == null || nums.length == 0) {
return result;
}
Arrays.sort(nums);
while (true) {
// step1: add list to result
List<Integer> list = new ArrayList<Integer>();
for (int i : nums) {
list.add(i);
}
result.add(list);
// step2: find nums[k] < nums[k + 1] backward
int k = -1;
for (int i = nums.length - 2; i >= 0; i--) {
if (nums[i] < nums[i + 1]) {
k = i;
break;
}
}
if (k == -1) break;
// step3: swap with nums[l]
int l = nums.length - 1;
while (l > k && nums[l] <= nums[k]) {
l--;
}
int temp = nums[l];
nums[l] = nums[k];
nums[k] = temp;
// step4: reverse between k+1, nums.length - 1
reverse(nums, k + 1, nums.length - 1);
}
return result;
}
private void reverse(int[] nums, int lb, int ub) {
while (lb < ub) {
int temp = nums[lb];
nums[lb] = nums[ub];
nums[ub] = temp;
lb++;
ub--;
}
}
}
~~~
### 源码分析
见前一题,略。
### 复杂度分析
略
### Reference
- [Permutation II | 九章算法](http://www.jiuzhang.com/solutions/permutations-ii/)
- Preface
- Part I - Basics
- Basics Data Structure
- String
- Linked List
- Binary Tree
- Huffman Compression
- Queue
- Heap
- Stack
- Set
- Map
- Graph
- Basics Sorting
- Bubble Sort
- Selection Sort
- Insertion Sort
- Merge Sort
- Quick Sort
- Heap Sort
- Bucket Sort
- Counting Sort
- Radix Sort
- Basics Algorithm
- Divide and Conquer
- Binary Search
- Math
- Greatest Common Divisor
- Prime
- Knapsack
- Probability
- Shuffle
- Basics Misc
- Bit Manipulation
- Part II - Coding
- String
- strStr
- Two Strings Are Anagrams
- Compare Strings
- Anagrams
- Longest Common Substring
- Rotate String
- Reverse Words in a String
- Valid Palindrome
- Longest Palindromic Substring
- Space Replacement
- Wildcard Matching
- Length of Last Word
- Count and Say
- Integer Array
- Remove Element
- Zero Sum Subarray
- Subarray Sum K
- Subarray Sum Closest
- Recover Rotated Sorted Array
- Product of Array Exclude Itself
- Partition Array
- First Missing Positive
- 2 Sum
- 3 Sum
- 3 Sum Closest
- Remove Duplicates from Sorted Array
- Remove Duplicates from Sorted Array II
- Merge Sorted Array
- Merge Sorted Array II
- Median
- Partition Array by Odd and Even
- Kth Largest Element
- Binary Search
- Binary Search
- Search Insert Position
- Search for a Range
- First Bad Version
- Search a 2D Matrix
- Search a 2D Matrix II
- Find Peak Element
- Search in Rotated Sorted Array
- Search in Rotated Sorted Array II
- Find Minimum in Rotated Sorted Array
- Find Minimum in Rotated Sorted Array II
- Median of two Sorted Arrays
- Sqrt x
- Wood Cut
- Math and Bit Manipulation
- Single Number
- Single Number II
- Single Number III
- O1 Check Power of 2
- Convert Integer A to Integer B
- Factorial Trailing Zeroes
- Unique Binary Search Trees
- Update Bits
- Fast Power
- Hash Function
- Count 1 in Binary
- Fibonacci
- A plus B Problem
- Print Numbers by Recursion
- Majority Number
- Majority Number II
- Majority Number III
- Digit Counts
- Ugly Number
- Plus One
- Linked List
- Remove Duplicates from Sorted List
- Remove Duplicates from Sorted List II
- Remove Duplicates from Unsorted List
- Partition List
- Two Lists Sum
- Two Lists Sum Advanced
- Remove Nth Node From End of List
- Linked List Cycle
- Linked List Cycle II
- Reverse Linked List
- Reverse Linked List II
- Merge Two Sorted Lists
- Merge k Sorted Lists
- Reorder List
- Copy List with Random Pointer
- Sort List
- Insertion Sort List
- Check if a singly linked list is palindrome
- Delete Node in the Middle of Singly Linked List
- Rotate List
- Swap Nodes in Pairs
- Remove Linked List Elements
- Binary Tree
- Binary Tree Preorder Traversal
- Binary Tree Inorder Traversal
- Binary Tree Postorder Traversal
- Binary Tree Level Order Traversal
- Binary Tree Level Order Traversal II
- Maximum Depth of Binary Tree
- Balanced Binary Tree
- Binary Tree Maximum Path Sum
- Lowest Common Ancestor
- Invert Binary Tree
- Diameter of a Binary Tree
- Construct Binary Tree from Preorder and Inorder Traversal
- Construct Binary Tree from Inorder and Postorder Traversal
- Subtree
- Binary Tree Zigzag Level Order Traversal
- Binary Tree Serialization
- Binary Search Tree
- Insert Node in a Binary Search Tree
- Validate Binary Search Tree
- Search Range in Binary Search Tree
- Convert Sorted Array to Binary Search Tree
- Convert Sorted List to Binary Search Tree
- Binary Search Tree Iterator
- Exhaustive Search
- Subsets
- Unique Subsets
- Permutations
- Unique Permutations
- Next Permutation
- Previous Permuation
- Unique Binary Search Trees II
- Permutation Index
- Permutation Index II
- Permutation Sequence
- Palindrome Partitioning
- Combinations
- Combination Sum
- Combination Sum II
- Minimum Depth of Binary Tree
- Word Search
- Dynamic Programming
- Triangle
- Backpack
- Backpack II
- Minimum Path Sum
- Unique Paths
- Unique Paths II
- Climbing Stairs
- Jump Game
- Word Break
- Longest Increasing Subsequence
- Palindrome Partitioning II
- Longest Common Subsequence
- Edit Distance
- Jump Game II
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock II
- Best Time to Buy and Sell Stock III
- Best Time to Buy and Sell Stock IV
- Distinct Subsequences
- Interleaving String
- Maximum Subarray
- Maximum Subarray II
- Longest Increasing Continuous subsequence
- Longest Increasing Continuous subsequence II
- Graph
- Find the Connected Component in the Undirected Graph
- Route Between Two Nodes in Graph
- Topological Sorting
- Word Ladder
- Bipartial Graph Part I
- Data Structure
- Implement Queue by Two Stacks
- Min Stack
- Sliding Window Maximum
- Longest Words
- Heapify
- Problem Misc
- Nuts and Bolts Problem
- String to Integer
- Insert Interval
- Merge Intervals
- Minimum Subarray
- Matrix Zigzag Traversal
- Valid Sudoku
- Add Binary
- Reverse Integer
- Gray Code
- Find the Missing Number
- Minimum Window Substring
- Continuous Subarray Sum
- Continuous Subarray Sum II
- Longest Consecutive Sequence
- Part III - Contest
- Google APAC
- APAC 2015 Round B
- Problem A. Password Attacker
- Microsoft
- Microsoft 2015 April
- Problem A. Magic Box
- Problem B. Professor Q's Software
- Problem C. Islands Travel
- Problem D. Recruitment
- Microsoft 2015 April 2
- Problem A. Lucky Substrings
- Problem B. Numeric Keypad
- Problem C. Spring Outing
- Microsoft 2015 September 2
- Problem A. Farthest Point
- Appendix I Interview and Resume
- Interview
- Resume