欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

leetcode17:Letter Combinations of a Phone Number

程序员文章站 2022-06-02 22:16:52
...

leetcode17:Letter Combinations of a Phone Number

思路:采用深度优先遍历来做,需要通过变量记录输入的数字串的位置。

public class LetterCombinationsofaPhoneNumber17 {

	public static void main(String[] args) {
		String digits = "23";
		System.out.println(letterCombinations(digits));
	}

	public static List<String> letterCombinations(String digits) {
		List<String> list = new ArrayList<>();
		if (digits == null || digits.length() == 0)
			return list;
		String[] s = { "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz" };
		StringBuilder sb = new StringBuilder();
		dfs(digits, 0, s, sb, list);
		return list;
	}

	public static void dfs(String digits, int digitIdx, String[] s, StringBuilder sb, List<String> list) {
		if (digits.length() == sb.length()) {
			list.add(new String(sb.toString()));
			return;
		}
		//注意此处下标的位置
		String str = s[digits.charAt(digitIdx)-'2'];
		for (int i = 0; i < str.length(); i++) {
			sb.append(str.charAt(i));
			dfs(digits, digitIdx + 1, s, sb, list);
			sb.deleteCharAt(sb.length() - 1);
		}
	}
}

输出:[ad, ae, af, bd, be, bf, cd, ce, cf]