Skip to content

Latest commit

 

History

History
67 lines (49 loc) · 949 Bytes

46. Permutations.md

File metadata and controls

67 lines (49 loc) · 949 Bytes

46. Permutations

  • Difficulty: Medium.
  • Related Topics: Backtracking.
  • Similar Questions: Next Permutation, Permutations II, Permutation Sequence, Combinations.

Problem

Given a collection of distinct integers, return all possible permutations.

Example:

Input: [1,2,3]
Output:
[
  [1,2,3],
  [1,3,2],
  [2,1,3],
  [2,3,1],
  [3,1,2],
  [3,2,1]
]

Solution

/**
 * @param {number[]} nums
 * @return {number[][]}
 */
var permute = function(nums) {
  var res = [];

  dfs(res, [], nums);

  return res;
};

var dfs = function (res, arr, nums) {
  var len = nums.length;
  var tmp1 = null;
  var tmp2 = null;

  if (!len) return res.push(arr);

  for (var i = 0; i < len; i++) {
    tmp1 = Array.from(arr);
    tmp1.push(nums[i]);

    tmp2 = Array.from(nums);
    tmp2.splice(i, 1);

    dfs(res, tmp1, tmp2);
  }
};

Explain:

nope.

Complexity:

  • Time complexity : O(n!).
  • Space complexity :