1. 程式人生 > >46. Permutations

46. Permutations

range == lock deep clas follow deepcopy list result

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

題解

該題是求所有可能的排列組合,是一道典型的dfs類型的題

代碼(python實現)

import copy
class Solution(object):
    def permute(self, nums):
        
""" :type nums: List[int] :rtype: List[List[int]] """ if nums is None: return results = [] if len(nums) == 0: return results self.helper(nums, results, []) return results def helper(self, nums, results, list):
if len(list) == len(nums): #註意此處是深度拷貝,如果用java語言寫則以list為輸入new出一個新的實例 results.append(copy.deepcopy(list)) return for i in range(len(nums)): if(nums[i] in list): continue list.append(nums[i]) self.helper(nums, results, list) list.pop()

46. Permutations