Leetcode 17. Letter Combinations of a Phone Number

在这里插入图片描述
方法1: backtracking/dfs。非常简单的一道题。复杂度分析如下:时间复杂:recursive tree一共有(3^n )* (4 ^m)个叶子结点,每个节点操作时间复杂1,n为代表三个字母的数字的个数,m为代表4个字母的数字的个数。空间复杂同时间复杂,空间复杂是归功于我们maintain的output,但是如果不考虑output的话,主要就是考虑recursive depth,那么空间复杂就为h了,h为原始input string的长度。

class Solution {
    public List<String> letterCombinations(String digits) {
        List<String> res = new ArrayList<>();
        if(digits.length() == 0) return res;
        StringBuilder path = new StringBuilder(); 
        Map<Integer,String[]> map = new HashMap<>();
        String[] arr2 = new String[]{"a", "b", "c"};
        String[] arr3 = new String[]{"d", "e", "f"};
        String[] arr4 = new String[]{"g", "h", "i"};
        String[] arr5 = new String[]{"j", "k", "l"};
        String[] arr6 = new String[]{"m", "n", "o"};
        String[] arr7 = new String[]{"p", "q", "r", "s"};
        String[] arr8 = new String[]{"t", "u", "v"};
        String[] arr9 = new String[]{"w", "x", "y", "z"};
        List<String[]> list = new ArrayList<>();
        list.add(arr2);
        list.add(arr3);
        list.add(arr4);
        list.add(arr5);
        list.add(arr6);
        list.add(arr7);
        list.add(arr8);
        list.add(arr9);
        for(int i = 2; i <= 9; i++){
            map.put(i, list.get(i-2));
        }
        backtracking(digits, 0, path, res, map);
        return res;
    }
    
    public void backtracking(String digits, int start,StringBuilder path, List<String> res, Map<Integer,String[]> map){
        if(start == digits.length()){
            StringBuilder ans = new StringBuilder(path);
            res.add(ans.toString());
            return; 
        }
        int digit = digits.charAt(start) - '0';
        String[] s = map.get(digit);
        for(String letter : s){
            path.append(letter);
            backtracking(digits, start+1, path, res, map);
            path.deleteCharAt(path.length()-1);
        }
    }
}

方法2: bfs-one queue。这是一个discussion区的高票回答,非常的巧妙。时间复杂(3^n )* (4 ^m), 空间复杂(3^n )* (4 ^m)。直接上代码:

class Solution {
    public List<String> letterCombinations(String digits) {
		LinkedList<String> res = new LinkedList<String>();
		if(digits.isEmpty()) return res;
		String[] mapping = new String[] {"0", "1", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
		res.add("");
		for(int i =0; i<digits.length(); i++){
			int x = digits.charAt(i) - '0';
			while(res.peek().length() == i){
				String t = res.remove();
				for(char s : mapping[x].toCharArray())
					res.add(t+s);
			}
		}
		return res;
	}

}

总结:

已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 终极编程指南 设计师:CSDN官方博客 返回首页