问题描述:

Given a digit string, 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.


示例:

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

问题分析:

这可以看作一个组合问题

1.设置一个结果集result值为空

2.对每个digit进行遍历,将其对应的字符添加分别与result结果集中的每个元素组合即可


下面是具体实现:

class Solution {
public:
    vector<string> letterCombinations(string digits) {
        vector<string> result;
        	if(digits.empty()) return vector<string>();
        	vector<string> v = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
        	result.push_back("");
        	
        	for(int i = 0; i  < digits.size(); i++)
        	{
        		int num = digits[i] - '0';
        		if(num < 0 || num > 9) break;
        		string candidate = v[num];
        		if(candidate.empty()) continue;//出现数字0和1 
        		vector<string> tmp;
				// 将result和candidate的字符串组合一下 
				for(int j = 0 ; j < candidate.size() ; j++) {
            		for(int k = 0 ; k < result.size() ; k++) {
                		tmp.push_back(result[k] + candidate[j]);
            		}
        		}
				result.swap(tmp); 
			}
			return result;
    }
};

好了,就先记这么多吧~


Logo

开放原子开发者工作坊旨在鼓励更多人参与开源活动,与志同道合的开发者们相互交流开发经验、分享开发心得、获取前沿技术趋势。工作坊有多种形式的开发者活动,如meetup、训练营等,主打技术交流,干货满满,真诚地邀请各位开发者共同参与!

更多推荐