题目:每一个数字对应着几个字母(1除外),对于一个不含“1”的字符串,字符串中的每一个数字随机一个其对应的字母,将所有字母组合在一起得到一个字符串,求所有这样的字符串。
“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
例如:“23”:输出"ad",“ae”,“af”,“bd”,“be”,“bf”,“cd”,“ce”,“cf”
题解(一):DFS(深度优先,depth first search)算法:利用递归算法得到每一个目标字符串,将目标字符串插入字符串数组并返回。
<script>
class solution{
constructor() {
this.map=new 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']]]);
this.res=""; //存储临时某一种情况下的字符集的字符串
this.result=[]; //目标字符串的集合
this.digits="";
}
trace(index)
{
//到达string digits的“尽头”后,得到一个目标字符串,插入结果数组中
if(index>=this.digits.length){this.result.push(this.res);return}
for(let i=0;i<this.map.get(this.digits[index]).length;i++)
{ //插入当前位置所存储的字符
this.res+=this.map.get(this.digits[index])[i];
//递归,直到string digits的“尽头”(递归会重复上一语句,相当于一直插入字符)
this.trace(index+1);
//将这个位置插入的字符删去,留出空间给其他情况下这个位置的字符,得到其他不同的目标字符串
this.res=this.res.substring(0,this.res.length-1);
}
}
returnList(input)
{
this.digits=input;
this.trace(0);
return this.result; //返回目标字符串的集合即结果集
}
}
var show=new solution();
for(let x of show.returnList("2"))
{
console.log(x);
}
</script>
题解(二)BFS(广度优先,breadth first search)算法:利用BFS算法模型,利用队列queue的特性,对字符串层层递进(遍历),遍历指针每得到一个数字,就利用队列存储目前(指针所指的位置之前的所有数字)能够组合而成的所有字符串,存储在队列中,并弹出之前的字符串,直到队列中的字符串为结果所需的字符串
class Solution {
public List<String> letterCombinations(String digits) {
if(digits.length()==0)
return new LinkedList<>();
HashMap<Character,char[]>map=new HashMap<>()
{{put('2',new char[]{'a','b','c'});
put('3',new char[]{'d','e','f'});
put('4',new char[]{'g','h','i'});
put('5',new char[]{'j','k','l'});
put('6',new char[]{'m','n','o'});
put('7',new char[]{'p','q','r','s'});
put('8',new char[]{'t','u','v'});
put('9',new char[]{'w','x','y','z'});}};
Queue<String>queue=new LinkedList<>();
for(int i=0;i<map.get(digits.charAt(0)).length;i++)
queue.add(map.get(digits.charAt(0))[i]+"");
for(int i=1;i<digits.length();i++){
int size= queue.size();
for(int k=0;k<size;k++){
String peek=queue.poll();
for(int j=0;j<map.get(digits.charAt(i)).length;j++){
queue.add(peek+map.get(digits.charAt(i))[j]);
}
}
}
return new LinkedList<>(queue);
}
}