leetcode day01

17. 电话号码的字母组合

给定一个仅包含数字 2-9 的字符串,返回所有它能表示的字母组合。答案可以按 任意顺序 返回。

给出数字到字母的映射如下(与电话按键相同)。注意 1 不对应任何字母。

1、是否可用一棵树,第一层为第一个数的所存的字母,每个节点连接下一个数字所存的所有字母(过于麻烦)。

2、问题是如何将不知道输入的数字的个数,如何判断循环的次数。(感觉是用递归


vector letterCombinations(string digits) {
	vectorcombinations;
	if (digits.size() == 0)
	{
		return combinations;
	}
	unordered_mapPhone_map{
		{'2', "abc"},
		{'3', "def"},
		{'4', "ghi"},
		{'5', "jkl"},
		{'6', "mno"},
		{'7', "pqrs"},
		{'8', "tuv"},
		{'9', "wxyz"}
	};
	string combination;
	backtrack(combination, combinations, 0, Phone_map, digits);
	return combinations;
}
void backtrack(string &combanation, vector &combinations,int index, unordered_map&Phone_map,string dights)
{
	if (index == dights.length())
	{
		combinations.push_back(combanation);
	}
	else
	{
		char dight = dights[index];
		string& letters = Phone_map.at(dight);
		for (char &letter:letters)
		{
			combanation.push_back(letter);
			backtrack(combanation, combinations, index + 1, Phone_map, dights);
			combanation.pop_back();
		}
	}
}

深度优先搜索

1、从上向下搜索

2、定义子问题,这道题实际就是一棵树,从上向下搜索,且记录已经搜索过的节点,直至最后一个,对其进行遍历,假设搜索到最后一层,在进行遍历时,此时的index=dight的长度。假设传入的数据为“23”,2就是3的上一层,最底层就是对3的遍历,下一步就是对2进行遍历。

3、递归第一步都是定义出口!

4、map.at()是返回key值所对应的value
 

总结

1、对递归不熟悉,虽然大概知道是用递归做,但是想法仍然停留在进行多次嵌套循环,如果需要进行多次嵌套循环时,大概率需要使用递归来。

2、深度优先搜索以及广度优先搜索怎么进行?

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