博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[LeetCode] Permutations II 解题报告
阅读量:6904 次
发布时间:2019-06-27

本文共 1738 字,大约阅读时间需要 5 分钟。

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].
[解题思路]
跟 Permutations的解法一样,就是要考虑“去重”。
先对数组进行排序,这样在DFS的时候,可以先判断前面的一个数是否和自己相等,相等的时候则前面的数必须使用了,自己才能使用,这样就不会产生重复的排列了。
与Permitations的code相比,只加了3行,Line 8,23,24。
[Code]
1:    vector
> permuteUnique(vector
&num) { 2: // Start typing your C/C++ solution below 3: // DO NOT write int main() function 4: vector
> coll; 5: vector
solution; 6: if(num.size() ==0) return coll; 7: vector
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
& num, int step, vector
& visited, vector
& solution, vector
>& 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.

转载于:https://www.cnblogs.com/codingtmd/archive/2012/12/30/5078977.html

你可能感兴趣的文章
Android新姿势:3D翻转效果原理
查看>>
Xtrabackup系列之:二进制安装
查看>>
Context []startup failed due to previous errors 错误
查看>>
RPM(RedHat Package Manager)
查看>>
iOS开源项目周报0302
查看>>
linux入门介绍
查看>>
JCaptcha报异常
查看>>
oracle dataguard 之nologing
查看>>
asp.net如何正确判断上传文件格式
查看>>
使用cocoaPods遇到Updating local specs repositories时的解决
查看>>
介绍几个常见的Git代码托管平台
查看>>
线上婚庆管理系统
查看>>
rpm包管理功能全解
查看>>
python变量的定义
查看>>
不害怕“早恋”:欣赏孩子的成熟
查看>>
Python面向对象
查看>>
从0到1,蘑菇街怎样打破应用运维自动化的技术藩篱
查看>>
【Django源码浅析】—Django runserver启动流程与URL路由
查看>>
Html5添加文件上传组件美化插件教程
查看>>
环路检测
查看>>