Leetcode: 46. Full permutation

topic

Given an array nums without repeating numbers, return all possible permutations of it. You can return answers in any order.

Example 1:

Input: nums = [1,2,3]
Output: [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1 ,2],[3,2,1]]
Example 2:

Input: nums = [0,1]
Output: [[0,1],[1,0]]
Example 3:

Input: nums = [1]
Output: [[1]]

Hint:
1 <= nums.length <= 6
-10 <= nums[i] <= 10
all integers in nums are different from each other

answer

The initial judgment uses depth traversal, that is, recursion.
Three elements of recursive function: parameter recursive boundary recursive entry
parameter: parameter uses an array to represent the currently selected number
Recursive boundary: when all the numbers in the array are selected, return to the previous
recursive entry: recursion has 3 entries 1 , 2, 3. (note the constraints)

code

var permute = function(nums) {
    //用于判断是否标记
    let use = {};
    //保存结果
    let ans = [];
    function dfs(path)
    {
        //递归边界
        if(path.length==nums.length)
        {
            ans.push(path.slice());
            return ;
        }
        //递归选择
        for(let i = 0; i < nums.length; i++)
        {
            if(use[i])
                continue;
            path.push(nums[i]);
            use[i] = true;
            dfs(path);
            path.pop();
            use[i] = false;
        }
    }
    dfs([])
    return ans;
};

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324771616&siteId=291194637
Recommended