Easy understanding JavaScript backtracking solution


  • 0
    I

    This version is very basic formal backtracking method. Just one thing I would like to mention that: make sure you shallow copy the list every time, because array is reference.

    /**
     * @param {number[]} nums
     * @return {number[][]}
     */
    var permute = function(nums) {
        // backtrack
        var list = [];
        permuteHelper(list, nums, 0);
        return list;
    };
    
    function permuteHelper(result, list, left){
        if(left >= list.length - 1){
            // shallow copy array
            result.push(list.slice());
        }else{
            for(var i = left; i < list.length; i++){
                swap(list, i, left);
                permuteHelper(result, list, left + 1);
                swap(list, i, left);
            }
        }
    }
    
    function swap(list, a, b){
        var temp = list[a];
        list[a] = list[b];
        list[b] = temp;
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.