46. Permutations 排列

 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]
]

  1. class Solution:
  2. def permute(self, nums):
  3. """
  4. :type nums: List[int]
  5. :rtype: List[List[int]]
  6. """
  7. res = []
  8. s = set(nums)
  9. def gen(l, added):
  10. if len(l) is len(nums):
  11. res.append(l[:])
  12. else:
  13. for i in s:
  14. if not i in added:
  15. l.append(i)
  16. added.add(i)
  17. gen(l, added)
  18. l.pop()
  19. added.remove(i)
  20. gen([], set())
  21. return res






posted @ 2018-02-05 23:17  xiejunzhao  阅读(134)  评论(0编辑  收藏  举报