1. 程式人生 > >46. Permutations (全排列)

46. Permutations (全排列)

col type -c 全排列 elf amp temp ble urn

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 (全排列)