- dfs with a for loop within
- permutation with backtracking
- same as combination sum, don't understand this intuitively
Solution
// from solutions// https://leetcode.com/problems/permutations/solutions/685868/dfs-backtracking-python-java-javascript-picture/// good illustration on how to approach the problem// time O(N^N), has to find every permutationvarpermute=function (nums) {let res = [];dfs(nums, [],Array(nums.length).fill(false), res);return res;};functiondfs(nums, path, used, res) {// console.log(path)if (path.length==nums.length) {// make a deep copy since otherwise we'd be append the same list over and overres.push(Array.from(path));return; }for (let i =0; i <nums.length; i++) {// skip used numsif (used[i]) continue;// add letter to permutation, mark letter as usedpath.push(nums[i]); used[i] =true;dfs(nums, path, used, res);// remove letter from permutation, mark letter as unusedpath.pop(); used[i] =false; }}