Lintcode425 Letter Combinations of a Phone Number solution 题解

【题目描述】

Given a digit string excluded 01, return all possible letter combinations that the number could represent.

A mapping of digit to letters (just like on the telephone buttons) is given below.

Lintcode425 Letter Combinations of a Phone Number solution 题解_第1张图片

 Notice

Although the above answer is in lexicographical order, your answer could be in any order you want.

给定一个数字字符串不包括01,返回所有可能表示的字母组合。

数字到字母的映射(就像电话上的按钮一样)。

注意事项

以上的答案是按照词典编撰顺序进行输出的,不过,在做本题时,你也可以任意选择你喜欢的输出顺序。

【题目链接】

www.lintcode.com/en/problem/letter-combinations-of-a-phone-number/

【题目解析】

这题思路还是挺明显的——搜索和 backtracking。和 subsets 有点类似不过不同的是每个组合只有达到最后一个数字所代表的那个组才可以加进结果。

每个数字对应的字母,我们用一个 map harcode 存起来然后用的时候直接查即可。

用 dfs 做,要知道我们已经到了哪一个数字所对应的字母,如果已经加完了最后一个我们则需要把当前加得到的东西存到 result 里。 我们可以用一个 variable digitIndex 来存当前到达的数字。 

e.g. 如果 input 是 “234” 则 digitIndex 从0 开始,没 traverse 一个数字我们加1,当 traverse 完最后一个数字以后 digitIndex = 3 即 input 的 size,这时候我们可以吧答案加进去。

可以把这个 这个过程想象成一个树, digitIndex就是树当前的 level。 最下一排的就是我们所要的结果

【参考答案】

www.jiuzhang.com/solutions/letter-combinations-of-a-phone-number/

你可能感兴趣的:(Lintcode425 Letter Combinations of a Phone Number solution 题解)