卖萌的弱渣

I am stupid, I am hungry.

Permutations

Given a list of numbers, return all possible permutations.

Example

For nums = [1,2,3], the permutations are:

1
2
3
4
5
6
7
8
[
  [1,2,3],
  [1,3,2],
  [2,1,3],
  [2,3,1],
  [3,1,2],
  [3,2,1]
]

Solution

(Permutations.py) download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
class Solution:
    """
    @param nums: A list of Integers.
    @return: A list of permutations.
    """
    def permute_helper(self,result,solution,nums):
        if len(nums)==0:
            result.append(solution[:])
            return
        for i in range(len(nums)):
            el = nums[i]
            solution.append(el)
            nums.pop(i)
            self.permute_helper(result,solution,nums)
            solution.pop()
            nums.insert(i,el)
        return


    def permute(self, nums):
        # write your code here
        result = []
        if nums == None or len(nums) == 0:
            return result
        self.permute_helper(result,[],nums)
        return result

if __name__ == "__main__":
    sol = Solution()
    sol.permute([1])