leetcode解题之 17. Letter Combinations of a Phone Number java 版(键盘排列)

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.

深度优先遍历

public List<String> letterCombinations(String digits) {
		List<String> list = new ArrayList<>();
		if (digits == null || digits.length() == 0)
			return list;
		char[] tmp = new char[digits.length()];
		String[] map = new String[] { "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz" };
		dfsSearch(digits, 0, map, tmp, list);
		return list;
	}
	private void dfsSearch(String digits, int idx, String[] map, char[] tmp, List<String> list) {
		if (idx == digits.length()) {
			list.add(new String(tmp));
			return;
		}
		// digits的第idx个字符cs - '2',正好为map数组的下标,
		// 获得对应的字符串,'2'和'abc'对应
		char cs = digits.charAt(idx);
		// 类似图的深度优先遍历,固定一个点,继续递归剩下的邻接点
		for (int i = 0; i < map[cs - '2'].length(); i++) {
			// 让每个字符做第一位,继续递归后面剩下的字符
			// 同一个层次的字符下标一样,都是idx
			tmp[idx] = map[cs - '2'].charAt(i);
			// 递归idx+1后面的字符
			dfsSearch(digits, idx + 1, map, tmp, list);
		}
	}
参考:http://blog.youkuaiyun.com/china_wanglong/article/details/38495355

附录:字符的全排列(参考)

public void PermutationHelper(char[] chars, int i, ArrayList<String> list) {
		if (i == chars.length) {
			list.add(String.valueOf(chars));
			return;
		}
		// 用于结果去重,可以用list
		Set<Character> charSet = new HashSet<Character>();
		for (int j = i; j < chars.length; ++j) {
			if (!charSet.contains(chars[j])) {
				charSet.add(chars[j]);
				swap(chars, i, j);// 交换
				PermutationHelper(chars, i + 1, list);
				swap(chars, i, j);// 复原
			}
		}
	}

	public void swap(char[] cs, int i, int j) {
		char temp = cs[i];
		cs[i] = cs[j];
		cs[j] = temp;
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值