我有一个关于 JavaScript 中电话键盘键的字母组合的问题。我使用 DFS 递归编写了一个解决方案。但它没有按预期工作。我是 JavaScript 的新手,但用 Ruby 编写的代码类似。
问题是关于从手机键盘获取所有可能的字母组合。
输入:“23”
输出:[“ad”、“ae”、“af”、“bd”、“be”、“bf”、“cd”、“ce”、“cf”]。
使用下面的代码,它停在“af”处。输出是 ["ad", "ae", "af"]。我不确定为什么这段代码没有移动到“2”的第二个字母,即“b”。
const map = {
"2": ["a", "b", "c"],
"3": ["d", "e", "f"],
"4": ["g", "h", "i"],
"5": ["j", "k", "l"],
"6": ["m", "n", "o"],
"7": ["p", "q", "r", "s"],
"8": ["t", "u", "v"],
"9": ["w", "x", "y", "z"]
};
let result = [];
let letterCombinations = function(digits) {
if (digits.length == 0) {
return []
};
let stack = [];
dfs(digits.split(''), 0, stack)
return result
};
function dfs(digits, index, stack) {
const currentLetters = map[digits[index]]
for (i = 0; i < currentLetters.length; i++) {
stack.push(currentLetters[i])
if (index == digits.length - 1) {
result.push(stack.join(''))
stack.pop()
} else {
dfs(digits, index + 1, stack)
stack.pop()
}
}
}
console.log(letterCombinations("23"));
最佳答案
需要申报i
在你的 for 循环中,否则它是全局的,并且在每个递归步骤中不断递增。
使用 for (let i = 0; i < currentLetters.length; i++)
const map = {
"2": ["a", "b", "c"],
"3": ["d", "e", "f"],
"4": ["g", "h", "i"],
"5": ["j", "k", "l"],
"6": ["m", "n", "o"],
"7": ["p", "q", "r", "s"],
"8": ["t", "u", "v"],
"9": ["w", "x", "y", "z"]
};
let result = [];
let letterCombinations = function(digits) {
if (digits.length == 0) {
return []
};
let stack = [];
dfs(digits.split(''), 0, stack)
return result
};
function dfs(digits, index, stack) {
const currentLetters = map[digits[index]]
// declare the loop variable!
for (let i = 0; i < currentLetters.length; i++) {
stack.push(currentLetters[i])
if (index == digits.length - 1) {
result.push(stack.join(''))
stack.pop()
} else {
dfs(digits, index + 1, stack)
stack.pop()
}
}
}
console.log(letterCombinations("23"));
关于javascript - 电话键盘按键的字母组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53840679/