DataStructure_Algorithm_HandBook_PreForLeetCode

46. Permutations

Given an array nums of distinct integers, return all the possible permutations. You can return the answer 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]]

Constraints:

solution

其实回溯可以分为组合和排列问题,如果是组合,那么顺序不一致的组合也是一样的,排列就是顺序不一样就是不一样的。

全排列是不能往后选的,因为往后选是选不到全部的元素,因此这里很明显不需要 index 了,只需要 path,然后我们要判断哪些元素选过。 我们可以开一个数组 used来判断。

出口就是path.length === nums.length 就可以了

var permute = function(nums) {
    let result = []; 
    dfs(new Array(nums.length).fill(false), [], nums, result);
    return result;
};

function dfs(used, path, nums, result) {
    if (path.length === nums.length) {
        result.push([...path]);
        return;
    }
    for (let i = 0; i < nums.length; i++) {
        if (!used[i]) {
            path.push(nums[i]);
            used[i] = true;
            dfs(used, path, nums, result);
            path.pop();
            // 注意重置 used[i]
            used[i] = false;
        }
    }
}