LeetCode Online Judge 题目C# 练习 - PermutationsII
2012-10-10 04:41
453 查看
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], and [2,1,1].
代码分析:
先把输入数组排列一下,利用之前做的一题,找下一个permutation的那一题,改写一下函数,如果找到返回true,然后再加入到结果里面。
For example,
[1,1,2] have the following unique permutations:
[1,1,2], [1,2,1], and [2,1,1].
public static List<List<int>> PermutationsII(List<int> num) { List<List<int>> ret = new List<List<int>>(); if (num.Count == 0) return ret; if (num.Count == 1) { ret.Add(num); return ret; } num.Sort(); ret.Add(new List<int>(num)); while(NextPermutationII(num)) ret.Add(new List<int>(num)); return ret; } public static bool NextPermutationII(List<int> num) { if (num.Count <= 1) return false; //find the falling edge int edge = -1; for (int i = num.Count - 2; i >= 0; i--) { if (num[i] < num[i + 1]) { edge = i; break; } } if (edge > -1) { //find replacement for (int i = edge + 1; i < num.Count; i++) { if (num[edge] >= num[i]) { NextPermutationSwap(num, edge, i - 1); break; } if (i == num.Count - 1) { NextPermutationSwap(num, edge, i); break; } } } else { return false; } for (int i = edge + 1, j = num.Count - 1; i <= edge + (num.Count - edge - 1) / 2; i++, j--) { NextPermutationSwap(num, i, j); } return true; }
代码分析:
先把输入数组排列一下,利用之前做的一题,找下一个permutation的那一题,改写一下函数,如果找到返回true,然后再加入到结果里面。
相关文章推荐
- LeetCode Online Judge 题目C# 练习 - Swap Nodes in Pairs
- LeetCode Online Judge 题目C# 练习 - Trapping Rain Water
- LeetCode Online Judge 题目C# 练习 - Container With Most Water
- LeetCode Online Judge 题目C# 练习 - Integer to Roman
- LeetCode Online Judge 题目C# 练习 - Sqrt(x)
- LeetCode Online Judge 题目C# 练习 - Jump Game
- LeetCode Online Judge 题目C# 练习 - Roman to Integer
- LeetCode Online Judge 题目C# 练习 - Search in Rotated Sorted Array
- LeetCode Online Judge 题目C# 练习 - Search in Rotated Sorted Array II
- LeetCode Online Judge 题目C# 练习 - Simplify Path
- LeetCode Online Judge 题目C# 练习 - Multiply Strings
- LeetCode Online Judge 题目C# 练习 - Remove Duplicates from Sorted Array
- LeetCode Online Judge 题目C# 练习 - Scramble String
- LeetCode Online Judge 题目C# 练习 - Unique Binary Search Trees
- LeetCode Online Judge 题目C# 练习 - Permutations
- LeetCode Online Judge 题目C# 练习 - Remove Duplicates from Sorted Array II
- LeetCode Online Judge 题目C# 练习 - Remove Duplicates from Sorted List
- LeetCode Online Judge 题目C# 练习 - Sort Color
- LeetCode Online Judge 题目C# 练习 - Longest Valid Parentheses
- LeetCode Online Judge 题目C# 练习 - Unique Paths II