这个求数组所有排列的公式是如何工作的?

问题描述 投票:0回答:0

我未能尝试获取给定数组的所有排列。对于数组,假设 [1,2 3],它应该返回 [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[ 3,1,2],[3,2,1]]。我无法让它与我的解决方案一起工作,所以我放弃了,我检查了其他人的解决方案,但无法理解它是如何工作的。

我不明白如果在它之前调用 dfs() ,这个函数如何到达 path.pop() 行。我也不知道这个循环将如何结束。有人可以解释一下吗?帮助

const permute = (nums) => {
    // Backtracking
    const used = new Set(); // Keep track of what we have used
    const path = []; // Current potiential answer array
    const res = []; // Result array to be returned
    
    const dfs = () => {
        // If path is same length as nums, we know we have an answer. Push it to res array
        if(path.length === nums.length) {
            res.push([...path]); // We use spread operator to clone since arrays are pass by reference
        }
        
        // Every DFS we loop all numbers
        for(let i = 0; i < nums.length; i++) {
            // We can skip these numbers if they have been used
            if(used.has(nums[i])) continue;
            
            // Add to our potienial answer array and make it used by adding to used set
            path.push(nums[i]);
            used.add(nums[i]);
            
            // After adding, we call DFS again. DFS will continue till we hit the base case above
            // Think of this as just continuing down a path till we have an answer
            dfs();
            
            // Once we pop out of DFS, we need to remove from path array and remove from used Set
            // This will let it be used later in further paths
            path.pop();
            used.delete(nums[i])
        }
        
    }
    
    // Start DFS
    // All variables are global, no need to pass in anything
    dfs();
    
    return res;
}```


I don't understand how this function ever reaches the path.pop() line if dfs() is called before it. I also don't see how this loop would ever end. Can someone please explain this? Help
javascript arrays recursion permutation
© www.soinside.com 2019 - 2024. All rights reserved.