Permutations
Given a collection of distinct integers, return all possible permutations. [#46]
Example: Input: [1,2,3] Output: [ [1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], [3,2,1] ]
题意:给定一个不重复的整数集,返回所有可能的排列。
使用现成的库函数:
>>> from itertools import permutations >>> permutations([1,2,3]) <itertools.permutations object at 0x039EE5A0> >>> [*permutations([1,2,3])] [(1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1)] >>> [*permutations([1,2,3,4])] [(1, 2, 3, 4), (1, 2, 4, 3), (1, 3, 2, 4), (1, 3, 4, 2), (1, 4, 2, 3), (1, 4, 3, 2), (2, 1, 3, 4), (2, 1, 4, 3), (2, 3, 1, 4), (2, 3, 4, 1), (2, 4, 1, 3), (2, 4, 3, 1), (3, 1, 2, 4), (3, 1, 4, 2), (3, 2, 1, 4), (3, 2, 4, 1), (3, 4, 1, 2), (3, 4, 2, 1), (4, 1, 2, 3), (4, 1, 3, 2), (4, 2, 1, 3), (4, 2, 3, 1), (4, 3, 1, 2), (4, 3, 2, 1)] >>>
自定义函数:
>>> def permute(nums): if len(nums) <= 1: return [nums] res = [] for i, num in enumerate(nums): n = nums[:i] + nums[i+1:] for x in permute(n): res.append([num]+ x) return res >>> permute([1,2,3]) [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]] >>> permute([1,2,3,4]) [[1, 2, 3, 4], [1, 2, 4, 3], [1, 3, 2, 4], [1, 3, 4, 2], [1, 4, 2, 3], [1, 4, 3, 2], [2, 1, 3, 4], [2, 1, 4, 3], [2, 3, 1, 4], [2, 3, 4, 1], [2, 4, 1, 3], [2, 4, 3, 1], [3, 1, 2, 4], [3, 1, 4, 2], [3, 2, 1, 4], [3, 2, 4, 1], [3, 4, 1, 2], [3, 4, 2, 1], [4, 1, 2, 3], [4, 1, 3, 2], [4, 2, 1, 3], [4, 2, 3, 1], [4, 3, 1, 2], [4, 3, 2, 1]] >>>
Permutations II
Given a collection of numbers that might contain duplicates, return all possible unique permutations. [#47]
Example: Input: [1,1,2] Output: [ [1,1,2], [1,2,1], [2,1,1] ]
题意:给定一个可能有重复数字的整数列表,返回所有可能的不重复排列。
使用现成的库函数,然后去重:
>>> from itertools import permutations >>> t = [*permutations([1,1,2])] >>> result = [] >>> [result.append(i) for i in t if i not in result] [None, None, None] >>> [list(i) for i in result] [[1, 1, 2], [1, 2, 1], [2, 1, 1]] >>>
自定义函数:只要在上一题的函数中加上判断 “if ([num]+ x) not in res:” 即可
>>> def permute(nums): if len(nums) <= 1: return [nums] res = [] for i, num in enumerate(nums): n = nums[:i] + nums[i+1:] for x in permute(n): if ([num]+ x) not in res: res.append([num]+ x) return res >>> permute([1,1,2]) [[1, 1, 2], [1, 2, 1], [2, 1, 1]] >>> permute([1,1,2,2]) [[1, 1, 2, 2], [1, 2, 1, 2], [1, 2, 2, 1], [2, 1, 1, 2], [2, 1, 2, 1], [2, 2, 1, 1]] >>>
相关单词
permutation
英 [ˌpɜːmjuˈteɪʃn] 美 [ˌpɜːrmjuˈteɪʃn]
n. 排列(方式);组合(方式);置换
permute
v. 改变…的序列;排列;交换;变更;(滤砂)软化
前缀per- 贯穿
词根-mut- 改变,交换
distinct
英 [dɪˈstɪŋkt] 美 [dɪˈstɪŋkt]
adj.不同的;明显的;清晰的;清楚的;明白的;有区别的;不同种类的;确定无疑的;确切的
前缀dis- 分开
词根-tinct-(=stinct)刺;刺激
contain
英 [kənˈteɪn] 美 [kənˈteɪn]
vt.包含;含有;容纳;控制,克制,抑制(感情);防止…蔓延(或恶化)
前缀con- 加强
词根-tain- 拿住
duplicate
英 [ˈdjuːplɪkeɪt , ˈdjuːplɪkət] 美 [ˈduːplɪkeɪt , ˈduːplɪkət]
vt.复制;复印;复写;(尤指不必要时)重复,再做一次
adj.完全一样的;复制的;副本的
n.完全一样的东西;复制品;副本
前缀du- 二,双
词根-plic- 重复
后缀-ate- 使…
unique
英 [juˈniːk] 美 [juˈniːk]
adj.唯一的;独一无二的;独特的;罕见的;(某人、地或事物)独具的,特有的
前缀uni- 一的, 单的