题目
- 输入一个字符串,按字典序打印出该字符串中字符的所有排列。例如输入字符串abc,则打印出由字符a,b,c所能排列出来的所有字符串abc,acb,bac,bca,cab和cba
- leetcode链接:https://leetcode-cn.com/problems/zi-fu-chuan-de-pai-lie-lcof/
思路
- 回溯算法
代码
// js版本
/**
* @param {string} s
* @return {string[]}
*/
var permutation = function (s) {
const path = []
const result = []
const deepUsed = new Map()
function backtracking() {
if (path.length === s.length) {
result.push(path.join(''))
return
}
const currentUsed = new Map()
for (let i = 0; i < s.length; i++) {
if (currentUsed.has(s[i]) && currentUsed.get(s[i])) continue
if (deepUsed.has(i) && deepUsed.get(i)) continue
currentUsed.set(s[i], true)
path.push(s[i])
deepUsed.set(i, true)
backtracking()
deepUsed.set(i, false)
path.pop()
}
}
backtracking()
return result
}