码迷,mamicode.com
首页 > 其他好文 > 详细

46. Permutations (全排列)

时间:2018-02-14 19:58:17      阅读:146      评论:0      收藏:0      [点我收藏+]

标签:for   base   ons   solution   ber   例子   following   tin   col   

Given a collection of distinct numbers, return all possible permutations.

For example,
[1,2,3] have the following permutations:

[
  [1,2,3],
  [1,3,2],
  [2,1,3],
  [2,3,1],
  [3,1,2],
  [3,2,1]
]

 

 

 

运用递归。 1234为例子

for  i in 1234:

  1  +  234(的全排列)

  2  +  134(的全排列)

  3  +  124(的全排列)

  4   + 123 (的全排列)

对应程序的17行

 

 1 class Solution(object):
 2     def __init__(self):
 3         self.res = []
 4 
 5     def permute(self, nums):
 6         """
 7         :type nums: List[int]
 8         :rtype: List[List[int]]
 9         """
10         self.help(nums, 0, len(nums))
11 
12         return self.res
13 
14     def help(self, a, lo, hi):
15         if(lo == hi):
16             self.res.append(a[0:hi])
17         for i in range(lo, hi):
18             self.swap(a, i, lo)
19             self.help(a, lo + 1, hi)
20             self.swap(a, i, lo)
21     def swap(self, a, i, j):
22         temp = a[i]
23         a[i] = a[j]
24         a[j] = temp

 

46. Permutations (全排列)

标签:for   base   ons   solution   ber   例子   following   tin   col   

原文地址:https://www.cnblogs.com/zle1992/p/8448766.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!