题目简述:9宫格的输入法,给定输入,输出有多少种不同的可能。
思路:这是一道典型的回溯,题目难度不大,需要自己构建好map即可。
回溯
也可以用24行直接代替下面的3行
对于我来说,一般回溯的写法就是25-27行这样,需要一个显示的修改和撤销操作,但是对于这一题来说,操作的对象是字符串,是非引用对象,可以直接创造新值进行操作——第24行
DFS
var letterCombinations = function (digits) {
if (!digits.length) return []
let hash = new Map()
hash.set('2', ['a', 'b', 'c'])
hash.set('3', ['d', 'e', 'f'])
hash.set('4', ['g', 'h', 'i'])
hash.set('5', ['j', 'k', 'l'])
hash.set('6', ['m', 'n', 'o'])
hash.set('7', ['p', 'q', 'r', 's'])
hash.set('8', ['t', 'u', 'v'])
hash.set('9', ['w', 'x', 'y', 'z'])
let datas = (digits + '').split('')
let chars = []
datas.forEach(el => {
// 获取按键上的所有字母
chars.push(hash.get(el))
})
let res = []
var dfs = function (one, index) {
if (one.length === chars.length) {
res.push(one)
return
}
for (let i = 0; i < chars[index].length; ++i) {
// dfs(one + chars[index][i], index + 1)
one += chars[index][i]; // 选择
dfs(one, index + 1); // 递归调用
one = one.slice(0, -1); // 撤销选择
}
}
dfs('', 0)
return res
};
对于上面的理解,对于leetcode-22题也是一样的做法,没有额外的操作。
BFS
BFS的解法就比较好理解了,把上一次的结果,都加上一个字母即可,然后更新上一层
var letterCombinations = function (digits) {
if (!digits.length) return [];
let hash = new Map();
hash.set("2", ["a", "b", "c"]);
hash.set("3", ["d", "e", "f"]);
hash.set("4", ["g", "h", "i"]);
hash.set("5", ["j", "k", "l"]);
hash.set("6", ["m", "n", "o"]);
hash.set("7", ["p", "q", "r", "s"]);
hash.set("8", ["t", "u", "v"]);
hash.set("9", ["w", "x", "y", "z"]);
let queue = [''];
for(let digit of digits){
const letters = hash.get(digit)
let nextQueue = []
for(let combination of queue){
for(let letter of letters){
nextQueue.push(combination + letter)
}
}
queue = nextQueue
}
return queue;
};