LeetCode Permutaions II
2016-01-07 19:28
561 查看
LeetCode解题之Permutaions II
原题
输出一个有重复数字的数组的全排列。注意点:
重复数字的可能导致重复的排列
例子:
输入: nums = [1, 2, 1]
输出: [[1, 1, 2], [1, 2, 1], [2, 1, 1]]
解题思路
这道题是上一题 Permutations 的加强版,现在要考虑重复的数字了,采用了偷懒的办法,先把数组排序,遍历时直接无视重复的数字,在原来的基础上只要添加两行代码。AC源码
[code]class Solution(object): def permuteUnique(self, nums): """ :type nums: List[int] :rtype: List[List[int]] """ result = [] nums.sort() self.get_permute([], nums, result) return result def get_permute(self, current, num, result): if not num: result.append(current + []) return for i, v in enumerate(num): if i - 1 >= 0 and num[i] == num[i - 1]: continue current.append(num[i]) self.get_permute(current, num[:i] + num[i + 1:], result) current.pop() if __name__ == "__main__": assert Solution().permuteUnique([1, 2, 1]) == [[1, 1, 2], [1, 2, 1], [2, 1, 1]]
欢迎查看我的Github来获得相关源码。
相关文章推荐
- SVN Checkout Failed的解决办法
- ubuntu 使用Perl NET::SMTP 发送Email auth 失败
- pthread_cond_wait
- There is no default constructor available in xxx错误引发
- 应用Btrfs管理磁盘,应用mdadm管理磁盘(softraid),使用raid卡管理磁盘
- 服务启动报错
- Binder&AIDL
- rails权限管理—devise+cancan+rolify
- 人工智能学习笔记(一)命题逻辑
- QWidget,QMainWindow和QDialog的区别 .
- 论机器人的环境感知与智主移动-兼谈基于微分几何的人工智能
- LeetCode Permutaions
- LintCode: Number of Airplanes in the Sky
- [已解决]使用matplotlib生成jpg报错:encoder jpeg not available
- 处于CLOSE_WAIT和TIME_WAIT状态连接的原因及解决
- Baidu地图的相关开发经验
- Communications link failure
- YTU 1007: Redraiment猜想
- 解决has leaked ServiceConnection com.baidu.location.c@427b6780
- 实现Gmail邮箱翻转效果之ActionBar