Skip to content

Instantly share code, notes, and snippets.

@shsunmoonlee
Created April 17, 2019 19:57
Show Gist options
  • Save shsunmoonlee/34b95eeab62536b571d6f37947cfd126 to your computer and use it in GitHub Desktop.
Save shsunmoonlee/34b95eeab62536b571d6f37947cfd126 to your computer and use it in GitHub Desktop.
leetcode - permutations.js
/**
* @param {number[]} nums
* @return {number[][]}
*/
function swap(nums, i, j) {
let temp = nums[i]
nums[i] = nums[j]
nums[j] = temp
}
const indent = (length) => {
let str = ""
for(let i =0; i<length; i++) {
str +=" "
}
return str
}
const permuteHelper = (nums, chosen, answer) => {
// console.log(indent(chosen.length), "PermuteHelper", nums, ' ', chosen, ' ', answer)
if(nums.length === 0) {
answer.push(chosen)
// console.log(indent(chosen.length), "***PermuteHelper", nums, ' ', chosen, ' ', answer)
return
} else {
for(let i =0; i<nums.length; i++) {
// choose
chosen.push(nums[i])
// remove and explore
let removed = nums.splice(i,1)
permuteHelper(nums, [...chosen], answer)
// un-choose.
nums.splice(i,0, ...removed)
chosen.pop()
}
}
}
var permute = function(nums) {
let answer = []
permuteHelper(nums, [], answer)
// console.log(answer)
return answer
// console.log("inside permute", nums)
// for(let i =0; i<nums.length - 1; i++) {
// swap(nums, i, i+1)
// console.log("after swap", nums)
// permute(nums)
// swap(nums, i, i+1)
// }
};
// level 0
// 1,2,3
// level 1
// i=0
// 2,1,3
// 3,2,1
// i=1
// 1,3,2
// i=2
// level 2
// i=0
// 1,2,3
// 3,1,2
// i=1
// 3,1,2
// 2,3,1
// i=2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment