leetcode|17. Letter Combinations of a Phone Number

Given a string containing digits from 2-9 inclusive, 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. Note that 1 does not map to any letters.

Example:

Input: "23"
Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].

Note:

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

最初的想法很简单,只要几层循环套着就能得出结果了,但是在程序完成后不能修改嵌套的层数,但是到底输入了多少个数字又是在程序运行的时候才知道的,莫非,要用树吗?

其实使用的就是像树一样的广度优先搜索算法,只是没有树结构而已。

class Solution {
public:
    vector<string> letterCombinations(string digits) {
        string map[10]={"0","1","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
        vector<string> ans;
        if(digits.size()==0) return ans;
        ans.push_back("");  //4
        int now=0;
        for(int i=0;i<digits.length();i++){
            vector<string> temp;  //1
            string chars=map[digits[i]-'0'];  //2
            for(int a=0;a<chars.length();a++){
                for(int b=0;b<ans.size();b++){
                    temp.push_back(ans[b]+chars[a]);  //3
                }
            }
            ans=temp;
        }
        return ans;
    }
};

对代码中注释地方的理解
1.每次循环的结果都作为下一次循环的初始条件,找一个临时变量存放起来

2.C++对[ ]做了重载,所以可以用下标来读取字符串中的每一个字符,但是得出的结果是字符,需要-‘0’得到它真正的数值,这就是为什么第一次运行的时候报错map[50]数组越界。
3.+号,两个字符串直接相加

4.为了接下来的3处的第一次循环可以正常进行,所以push进去一个空字符。

最高赞的代码

public List<String> letterCombinations(String digits) {
		LinkedList<String> ans = new LinkedList<String>();
		if(digits.isEmpty()) return ans;
		String[] mapping = new String[] {"0", "1", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
		ans.add("");
		for(int i =0; i<digits.length();i++){
			int x = Character.getNumericValue(digits.charAt(i));
			while(ans.peek().length()==i){
				String t = ans.remove();
				for(char s : mapping[x].toCharArray())
					ans.add(t+s);
			}
		}
		return ans;
	}
同样用的是广度优先搜索的思想,但是直接用的是一个先入先出的队列,通过检查长度来确定是否这个循环已经结束。

猜你喜欢

转载自blog.csdn.net/xueying_2017/article/details/80471942
今日推荐