Skip to content

46. Permutations

https://leetcode.com/problems/permutations/

js
/**
 * @param {number[]} nums
 * @return {number[][]}
 */
var permute = function(nums) {
  if (nums.length === 1) {
    return [nums]
  }

  var result = []
  for (let i = 0; i < nums.length; i++) {
    var copy = nums.slice()
    var n = copy.splice(i, 1)[0]
    permute(copy).forEach(arr => {
      arr.unshift(n)
      result.push(arr)
    })
  }

  return result
}
py
class Solution(object):

    def permute(self, nums):
        """
        :type nums: List[int]
        :rtype: List[List[int]]
        """
        if len(nums) == 1:
            return [nums]
        result = []
        for i in range(len(nums)):
            for j in self.permute(nums[:i] + nums[i + 1:]):
                result.append([nums[i]] + j)
        return result