leetcode 017 —— 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"].

思路:简单的回溯法

class Solution {
public:
	vector<string> letterCombinations(string digits) {
		vector<string> table={"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
		vector<string> res;
		if (digits.empty()) return res;
		scan(0, "", digits, table, res);
		return res;

	}
	void scan(int level, string path, string &digits, vector<string> &table,vector<string> &res){
		if (level == digits.size()){
			res.push_back(path);
			return;
		}
		for (int i = 0; i < table[digits[level] - '0'].size(); i++){
			path.push_back(table[digits[level] - '0'][i]);
			scan(level + 1, path, digits, table, res);
			path.pop_back();
		}
	}
};


阅读更多
上一篇leetcode 016 —— 3Sum Closest
下一篇leetcode 018 —— 4Sum (nsum)
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭