• 17. Letter Combinations of a Phone Number


    欢迎fork and star:Nowcoder-Repository-github

    17. Letter Combinations of a Phone Number

    题目

    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"].
    
    Note:
    Although the above answer is in lexicographical order, your answer could be in any order you want. 
    
    

    解析

    • 可以迭代,即依次读取字符串中的每位数字,然后把数字对应的字母依次加到当前的所有结果中,然后进入下一次迭代。也可以用递归来解,思路也类似,就是对于当前已有的字符串,递归剩下的数字串,然后得到结果后加上去。假设输入字符串总共有n个数字,平均每个数字可以代表m个字符,那么时间复杂度是O(m^n),确切点是输入字符串中每个数字对应字母数量的乘积,即结果的数量,空间复杂度也是一样。时间复杂度:O(m^n);空间复杂度:O(m^n)
    // 17. Letter Combinations of a Phone Number
    class Solution_17 {
    public:
    
    	// map<int, string> num2alp = { { 2, "abc" }, { 3, "def" }, { 4, "ghi" }, { 5, "jkl" }, { 6, "mno" }, { 7, "pqrs" }, { 8, "tuv" }, { 9, "wxyz" } };
    	/*static const*/ vector<string> v = { "", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz" };
    	void help(string digits,vector<string> &vec,string &temp,int index,int n)
    	{
    		if (index==n)
    		{
    			vec.push_back(temp);
    			return;
    		}
    		string str = v[digits[index]-'0'];
    		
    		for (int i = 0; i < str.size();i++)
    		{
    			temp.push_back(str[i]);
    			help(digits, vec,temp, index + 1,n);
    			temp.pop_back();
    		}
    		return;
    	}
    
    	// 回溯递归实现
    	vector<string> letterCombinations(string digits) { //23
    		vector<string> vec;
    		string temp;
    		if (digits.size()==0)
    		{
    			vec.push_back(""); //初始化一个空
    			return vec;
    		}
    
    		help(digits,vec,temp,0,digits.size());
    
    		return vec;
    	}
    
          // 迭代实现
    	vector<string> letterCombinations_ref(string digits) {
    		vector<string> result;
    		if (digits.empty()) return vector<string>();
    		static const vector<string> v = { "", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz" };
    		result.push_back("");   // add a seed for the initial case
    		for (int i = 0; i < digits.size(); ++i) {
    			int num = digits[i] - '0';
    			if (num < 0 || num > 9) break;
    			const string& candidate = v[num];
    			if (candidate.empty()) continue;
    			vector<string> tmp;
    			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;
    	}
    
    };
    
    
    

    题目来源

  • 相关阅读:
    C# 对串口的操作
    【STM32】手册理解
    【LCD MENU】710
    【交流采集——RMS(均方根)】电压和电流
    【DMA】配置及使用
    【ADC】ADC初始化的注意事项
    【电源】开关型功率变换器的基本结构
    【单片机】【710】逆变
    【单片机】【710】PWM
    【单片机】【710】振荡器和系统时钟
  • 原文地址:https://www.cnblogs.com/ranjiewen/p/8323822.html
Copyright © 2020-2023  润新知