Skip to content

Latest commit

 

History

History
45 lines (37 loc) · 1.02 KB

File metadata and controls

45 lines (37 loc) · 1.02 KB

-- 回溯 - mid 点击直达力扣

给定一个不含重复数字的数组 nums ,返回其 所有可能的全排列 。你可以 按任意顺序 返回答案。

示例 1:

输入:nums = [1,2,3]
输出:[[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]

示例 2:

输入:nums = [0,1]
输出:[[0,1],[1,0]]
// 排列问题:回溯
let path = []
let result = []

function permute(nums: number[]): number[][] {
    result = []
    let used = new Array(nums.length)
    used.fill(false)
    backTracking(nums, used)
    return result
};

function backTracking(nums: number[], used: boolean[]): void {
    if (path.length === nums.length) {
        result.push([...path])
        return
    }
    for (let i = 0; i < nums.length; i++) {
        if (used[i] === true) {
            continue
        }
        used[i] = true
        path.push(nums[i])
        backTracking(nums, used)
        used[i] = false
        path.pop()
    }
}