# [Leetcode][python]Permutations/全排列

146 篇文章 4 订阅
145 篇文章 13 订阅

### 代码

#### 递归

class Solution(object):
def permute(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
self.res = []
sub = []
self.dfs(nums,sub)
return self.res

def dfs(self, Nums, subList):
if len(subList) == len(Nums):
#print res,subList
self.res.append(subList[:])
for m in Nums:
if m in subList:
continue
subList.append(m)
self.dfs(Nums,subList)
subList.remove(m)

#### 递归方法二

n = nums[:i] + nums[i+1:]
n = BC
n = A + C = AC
n = AB

class Solution(object):

def permute(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
print 'nums', nums
if len(nums) <= 1:
return [nums]
ans = []
for i, num in enumerate(nums):
n = nums[:i] + nums[i+1:]  # n是剩余数的list
print nums[:i], '+', nums[i+1:], '=', n
for y in self.permute(n):  # 直到函数有return，一个数的时候[nums]，所以y是list
print '递归内：'
print [num], '+', y, '=',[num] + y
ans.append([num] + y)
print '-----End-----'
return ans


nums [1, 2, 3]
[] + [2, 3] = [2, 3]
nums [2, 3]
[] + [3] = [3]
nums [3]

[2] + [3] = [2, 3]
-----End-----
[2] + [] = [2]
nums [2]

[3] + [2] = [3, 2]
-----End-----

[1] + [2, 3] = [1, 2, 3]

[1] + [3, 2] = [1, 3, 2]
-----End-----
[1] + [3] = [1, 3]
nums [1, 3]
[] + [3] = [3]
nums [3]

[1] + [3] = [1, 3]
-----End-----
[1] + [] = [1]
nums [1]

[3] + [1] = [3, 1]
-----End-----

[2] + [1, 3] = [2, 1, 3]

[2] + [3, 1] = [2, 3, 1]
-----End-----
[1, 2] + [] = [1, 2]
nums [1, 2]
[] + [2] = [2]
nums [2]

[1] + [2] = [1, 2]
-----End-----
[1] + [] = [1]
nums [1]

[2] + [1] = [2, 1]
-----End-----

[3] + [1, 2] = [3, 1, 2]

[3] + [2, 1] = [3, 2, 1]
-----End-----

class Solution(object):
def permute(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
print 'nums', nums
if len(nums) <= 1:
return [nums]
ans = []
for i, num in enumerate(nums):
n = nums[:i] + nums[i+1:]
for temp_list in self.permute(n):
ans.append([num] + temp_list)
print '-----End-----'
return ans

• 1
点赞
• 1
收藏
觉得还不错? 一键收藏
• 0
评论
07-12 1000
03-02 104
04-26 4850
03-22 274
11-11 6420
10-30 973
04-20 513
04-24 133
04-19 487

### “相关推荐”对你有帮助么？

• 非常没帮助
• 没帮助
• 一般
• 有帮助
• 非常有帮助

1.余额是钱包充值的虚拟货币，按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载，可以购买VIP、付费专栏及课程。