Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // 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]
- // ]
- /**
- * @param {number[]} nums
- * @return {number[][]}
- */
- var permute = function(nums) {
- helpPermute(nums, []);
- };
- var helpPermute = function(av, curr) {
- if(av.length === 0) {
- console.log(curr);
- return;
- }
- for(var x = 0; x < av.length; x++) {
- //BACKTRACKING PARADIGM:
- //1. Choose an option
- curr.push(av[x]);
- av.splice(x, 1);
- //2. Explore the possibilities with that option
- helpPermute(av, curr);
- //3. Unchoose that option and go to the next one
- var popIt = curr.pop();
- av.splice(x, 0, popIt);
- }
- }
Add Comment
Please, Sign In to add comment