给定一个仅包含数字 2-9 的字符串,返回所有它能表示的字母组合。答案可以按 任意顺序 返回。
给出数字到字母的映射如下(与电话按键相同)。注意 1 不对应任何字母。
这个题目我纠结半天,想了想,我只会用树做
下面贴代码
/**
* @param {string} digits
* @return {string[]}
*/
class Ss {
constructor(val) {
this.left = undefined
this.right = undefined
this.center = undefined
this.centerl = undefined
this.val = val
}
add(value1, value2, value3, value4) {
if (this.left != undefined) {
this.left.add(value1, value2, value3, value4)
this.right.add(value1, value2, value3, value4)
this.center.add(value1, value2, value3, value4)
if (this.centerl != undefined) {
this.centerl.add(value1, value2, value3, value4)
}
}
if (this.left == undefined) {
this.left = new Ss(value1)
this.right = new Ss(value2)
this.center = new Ss(value3)
if (value4 != undefined) {
this.centerl = new Ss(value4)
}
}
}
toString(x, ko) {
if (this.val == undefined) {
return x
}
x += this.val
if (this.left != undefined) {
this.left.toString(x, ko)
}
if (this.right != undefined) {
this.right.toString(x, ko)
}
if (this.center != undefined) {
this.center.toString(x, ko)
}
if (this.centerl != undefined) {
this.centerl.toString(x, ko)
}
ko.push(x)
}
}
let obj = {
'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'],
};
var letterCombinations = function(digits) {
var ko = []
if (digits == "") {
return []
}
digits = digits.split("")
let us = []
let num = 2
let tree = new Ss("")
for (let i = 0; i < digits.length; i++) {
tree.add(...obj[digits[i]])
}
tree.toString("", ko)
ko = ko.filter(num => num.length >= digits.length)
return ko
};
欢迎各位大佬点评,我想提升下效率。