JavaScript data structures and algorithms - BFS, DFS, backtracking

Article directory

BFS

pending upgrade

DFS

Classic example:

full array

Leetour 46: Full Arrangement
Recommended Video
Diagram
insert image description here

 * 力扣46:全排列
 * @param {
    
    *} nums 
 */
var permute = function (nums) {
    
    
    let visited = new Array(nums.length).fill(false)
    let reslut = []
    let dfs = (nums, depth, len, path, visited) => {
    
    
        if (depth == nums.length) {
    
    
            reslut.push([...path])
        }
        for (let i = 0; i < len; i++) {
    
    
            if (!visited[i]) {
    
    
                path.push(nums[i])
                visited[i] = true
                dfs(nums, depth + 1, len, path, visited)
                visited[i] = false
                path.pop()
            }
        }
    }
    dfs(nums, 0, nums.length, [], visited)
    return reslut
};

I struggled with two questions before:
1: When and how to switch from 1-2-3 to 1-3-2, especially the switch between 2 and 3 nodes. It can be seen from the above picture that it is the violent for loop
2: the order of backtracking: I will give an example in this question. When I
just finished 1-2-3 , the backtracking of the two visited is **[true,false,false] , At this time, the i of the second layer of for loop is 2**, which is followed by 3 in [1,2,3] , and then referring to visited
will select 2** in **[1,2,3].
insert image description here
Power button 17: The combination of letters of the phone number

Guess you like

Origin blog.csdn.net/qq_45859670/article/details/123388158