LeetCode17. 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.


class Solution {
public:
	vector letterCombinations(string digits) {
		vector vs;
		if (digits.size() == 0) {
			return vs;
		}
		else if (digits.size() == 1) {
			for (char c : nums[digits[0] - '0']) {
				vs.emplace_back(string(1, c));
			}
			return vs;
		}
		else {
			auto&& pvs = letterCombinations(digits.substr(1));
			for (char c : nums[digits[0] - '0']) {
				for (string& s : pvs) {
					vs.emplace_back(string(1, c) + s);
				}
			}
			return vs;
		}
	}
private:
	string nums[10] = {
		"",
		"",
		"abc",
		"def",
		"ghi",
		"jkl",
		"mno",
		"pqrs",
		"tuv",
		"wxyz",
	};
};


你可能感兴趣的:(面试题算法题)