GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • LeetCodeJavascript.com
  • Star on GitHub

This view

  • Original page
  • New address

GeezerVison is showing leetcodejavascript.com — #46 - Permutations - LeetCode JavaScript Solutions

Back to all solutions

#46 - Permutations

Medium • View on LeetCode • View on GitHub
Array Backtracking

Problem Description

Given an array nums of distinct integers, return all the possible permutations.

You can return the answer in any order.

Solution

/**
 * @param {number[]} nums
 * @return {number[][]}
 */
var permute = function(nums) {
  const result = [];
  backtrack(result, nums);
  return result;
};

function backtrack(result, nums, order = []) {
  if (!nums.length) {
    result.push(order);
  } else {
    for (let i = 0; i < nums.length; i++) {
      backtrack(
        result,
        [...nums.slice(0, i), ...nums.slice(i + 1)],
        [...order, nums[i]]
      );
    }
  }
}
You are visitor 01402503 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.