Guest User

Untitled

a guest
May 24th, 2018
99
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.78 KB | None | 0 0
  1. // Given a collection of distinct integers, return all possible permutations.
  2.  
  3. // Example:
  4.  
  5. // Input: [1,2,3]
  6. // Output:
  7. // [
  8. // [1,2,3],
  9. // [1,3,2],
  10. // [2,1,3],
  11. // [2,3,1],
  12. // [3,1,2],
  13. // [3,2,1]
  14. // ]
  15.  
  16. /**
  17. * @param {number[]} nums
  18. * @return {number[][]}
  19. */
  20. var permute = function(nums) {
  21. helpPermute(nums, []);
  22. };
  23.  
  24. var helpPermute = function(av, curr) {
  25. if(av.length === 0) {
  26. console.log(curr);
  27. return;
  28. }
  29. for(var x = 0; x < av.length; x++) {
  30. //BACKTRACKING PARADIGM:
  31. //1. Choose an option
  32. curr.push(av[x]);
  33. av.splice(x, 1);
  34. //2. Explore the possibilities with that option
  35. helpPermute(av, curr);
  36. //3. Unchoose that option and go to the next one
  37. var popIt = curr.pop();
  38. av.splice(x, 0, popIt);
  39. }
  40. }
Add Comment
Please, Sign In to add comment