Algorithm: Backtracking solves the problem of finding all permutations of a given string

All sorts of strings

List all sorts of a given string. This problem is usually called permutations in English
and the method used is backtracking

The specific operations are:

Swap each bit of the string with each bit of the string including itself, until there are no characters that can be exchanged with it, output the current string, and return to the previous node to try to swap The next possible character. Until all leaf nodes are output, all possible orderings are obtained.

Use visualization to see the solution steps of the retrospective:
Backtracking

The entire process of finding the final output can be seen as the process of a tree extending downwards. All the final leaf nodes of this tree are the outputs we care about. After understanding the backtracking process, the code is ready to come out. Here is js The version of the algorithm to find all sorts:

/**
 * @param {string} s
 */
var permutations = function(s) {
    
    
  const length = s.length
  backtracking(s, 0, length - 1)
}

var backtracking = function(s, l, r) {
    
    
  // 当i和j相同,说明除了自身以外已没有可调换数字,直接输出当前字符串
  if (i === j) {
    
    
    console.log(s)
  } else {
    
     // 否则,继续构造回溯树
    for (let i = l; i <= r; i++) {
    
    
      s = swap(s, l, i)
      backtracking(s, l + 1, r)
      // 把s还原成swap之前的字符串,准备交换下一个字符
      s = swap(s, l, i)
    }
  }
}

// 将字符串a的i和j字符调换位置
var swap = function(a, i, j) {
    
    
  var charArray = a.split('')
  var tempChar = charArray[i]
  charArray[i] = charArray[j]
  charArray[j] = tempChar
  return charArray.join('')
}

Guess you like

Origin blog.csdn.net/qq_35714301/article/details/113503468