# Permutation Index II
### Source
- lintcode: [(198) Permutation Index II](http://www.lintcode.com/en/problem/permutation-index-ii/)
~~~
Given a permutation which may contain repeated numbers,
find its index in all the permutations of these numbers,
which are ordered in lexicographical order. The index begins at 1.
Example
Given the permutation [1, 4, 2, 2], return 3.
~~~
### 题解
题 [Permutation Index](http://algorithm.yuanbin.me/zh-cn/exhaustive_search/permutation_index.html) 的扩展,这里需要考虑重复元素,有无重复元素最大的区别在于原来的`1!, 2!, 3!...`等需要除以重复元素个数的阶乘,颇有点高中排列组合题的味道。记录重复元素个数同样需要动态更新,引入哈希表这个万能的工具较为方便。
### Python
~~~
class Solution:
# @param {int[]} A an integer array
# @return {long} a long integer
def permutationIndexII(self, A):
if A is None or len(A) == 0:
return 0
index = 1
factor = 1
for i in xrange(len(A) - 1, -1, -1):
hash_map = {A[i]: 1}
rank = 0
for j in xrange(i + 1, len(A)):
if A[j] in hash_map.keys():
hash_map[A[j]] += 1
else:
hash_map[A[j]] = 1
# get rank
if A[i] > A[j]:
rank += 1
index += rank * factor / self.dupPerm(hash_map)
factor *= (len(A) - i)
return index
def dupPerm(self, hash_map):
if hash_map is None or len(hash_map) == 0:
return 0
dup = 1
for val in hash_map.values():
dup *= self.factorial(val)
return dup
def factorial(self, n):
r = 1
for i in xrange(1, n + 1):
r *= i
return r
~~~
### C++
~~~
class Solution {
public:
/**
* @param A an integer array
* @return a long integer
*/
long long permutationIndexII(vector<int>& A) {
if (A.empty()) return 0;
long long index = 1;
long long factor = 1;
for (int i = A.size() - 1; i >= 0; --i) {
int rank = 0;
unordered_map<int, int> hash;
++hash[A[i]];
for (int j = i + 1; j < A.size(); ++j) {
++hash[A[j]];
if (A[i] > A[j]) {
++rank;
}
}
index += rank * factor / dupPerm(hash);
factor *= (A.size() - i);
}
return index;
}
private:
long long dupPerm(unordered_map<int, int> hash) {
if (hash.empty()) return 1;
long long dup = 1;
for (auto it = hash.begin(); it != hash.end(); ++it) {
dup *= fact(it->second);
}
return dup;
}
long long fact(int num) {
long long val = 1;
for (int i = 1; i <= num; ++i) {
val *= i;
}
return val;
}
};
~~~
### Java
~~~
public class Solution {
/**
* @param A an integer array
* @return a long integer
*/
public long permutationIndexII(int[] A) {
if (A == null || A.length == 0) return 0;
long index = 1;
long factor = 1;
for (int i = A.length - 1; i >= 0; i--) {
HashMap<Integer, Integer> hash = new HashMap<Integer, Integer>();
hash.put(A[i], 1);
int rank = 0;
for (int j = i + 1; j < A.length; j++) {
if (hash.containsKey(A[j])) {
hash.put(A[j], hash.get(A[j]) + 1);
} else {
hash.put(A[j], 1);
}
if (A[i] > A[j]) {
rank++;
}
}
index += rank * factor / dupPerm(hash);
factor *= (A.length - i);
}
return index;
}
private long dupPerm(HashMap<Integer, Integer> hash) {
if (hash == null || hash.isEmpty()) return 1;
long dup = 1;
for (int val : hash.values()) {
dup *= fact(val);
}
return dup;
}
private long fact(int num) {
long val = 1;
for (int i = 1; i <= num; i++) {
val *= i;
}
return val;
}
}
~~~
### 源码分析
在计算重复元素个数的阶乘时需要注意`dup *= fact(val);`, 而不是`dup *= val;`. 对元素`A[i]`需要加入哈希表 - `hash.put(A[i], 1);`,设想一下`2, 2, 1, 1`的计算即可知。
### 复杂度分析
双重 for 循环,时间复杂度为 O(n2)O(n^2)O(n2), 使用了哈希表,空间复杂度为 O(n)O(n)O(n).
- 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