[LeetCode] Permutations II 解题报告
来源:互联网 发布:大汉主义知乎 编辑:程序博客网 时间:2024/06/05 11:04
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]
.» Solve this problem
[解题思路]
跟 Permutations的解法一样,就是要考虑“去重”。先对数组进行排序,这样在DFS的时候,可以先判断前面的一个数是否和自己相等,相等的时候则前面的数必须使用了,自己才能使用,这样就不会产生重复的排列了。
与Permitations的code相比,只加了3行,Line 8,23,24。
[Code]
1: vector<vector<int> > permuteUnique(vector<int> &num) {
2: // Start typing your C/C++ solution below
3: // DO NOT write int main() function
4: vector<vector<int> > coll;
5: vector<int> solution;
6: if(num.size() ==0) return coll;
7: vector<int> visited(num.size(), 0);
8: sort(num.begin(), num.end());
9: GeneratePermute(num, 0, visited, solution, coll);
10: return coll;
11: }
12: void GeneratePermute(vector<int> & num, int step, vector<int>& visited, vector<int>& solution, vector<vector<int> >& coll)
13: {
14: if(step == num.size())
15: {
16: coll.push_back(solution);
17: return;
18: }
19: for(int i =0; i< num.size(); i++)
20: {
21: if(visited[i] == 0)
22: {
23: if(i>0 && num[i] == num[i-1]&& visited[i-1] ==0
)
24: continue;
25: visited[i] = 1;
26: solution.push_back(num[i]);
27: GeneratePermute(num, step+1, visited, solution, coll);
28: solution.pop_back();
29: visited[i] =0;
30: }
31: }
32: }
[Note]
Line 23: Don’t miss “&& visited[i-1] ==0”. Or, the inner recursion will skip using duplicate number.
0 0
- 【LeetCode】Permutations II 解题报告
- [LeetCode] Permutations II 解题报告
- Permutations II [Leetcode 解题报告]
- [leetcode] 47. Permutations II 解题报告
- [Leetcode] 47. Permutations II 解题报告
- [leetcode]47. Permutations II@Java解题报告
- [LeetCode]Permutations,解题报告
- 【LeetCode】Permutations 解题报告
- LeetCode-Permutations-解题报告
- [LeetCode] Permutations 解题报告
- Permutations [Leetcode 解题报告]
- Leetcode #47. Permutations II 全排列2 解题报告
- [leetcode] 46. Permutations 解题报告
- LeetCode 46. Permutations 解题报告
- [Leetcode] 46. Permutations 解题报告
- Leetcode # 46. Permutations 全排列 解题报告
- [leetcode]46. Permutations@Java解题报告
- leetcode解题方案--047--Permutations II
- [LeetCode] Pascal’s Triangle II 解题报告
- Android 之 Fresco 显示圆形图片 之坑
- [LeetCode] Path Sum II 解题报告
- [LeetCode] Permutations 解题报告
- Java环境变量的配置
- [LeetCode] Permutations II 解题报告
- [LeetCode] Plus One 解题报告
- [LeetCode] Populating Next Right Pointers in Each Node 解题报告
- [LeetCode] Populating Next Right Pointers in Each Node II 解题报告
- [LeetCode] Recover Binary Search Tree 解题报告
- [LeetCode] Pow(x, n) 解题报告
- [LeetCode] Remove Duplicates from Sorted Array 解题报告
- ANSYS SpaceClaim 2015中文免费版
- [LeetCode] Remove Duplicates from Sorted Array II 解题报告