这次题目:Letter Combinations of a Phone Number
这个题目没什么难度,倒是一开始不能确定0键对应的什么有点摸不到头脑。感觉这道题考察基本功吧,可以用递归,但最好还是用非递归再写一遍。
顺便吐槽一下,String的操作好复杂啊,尤其涉及到int char String 三者转换的时候,有时候用subString(0,1)这种都比CharAt(0)好一点,也是醉了。
还有就是,在写非递归的时候,在初始化res的时候,就可以往里面加一个空的字符串,这样在循环的时候省去if else的判断,属于自己没想到,以后注意。
递归:
public class Solution { public String[] letters = {"0", "1", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"}; public List<String> letterCombinations(String digits) { int len = digits.length(); List<String> res = new ArrayList<String>(); if(len == 0){ res.add(""); return res; } List<String> next = letterCombinations(digits.substring(1)); int p = Integer.parseInt(digits.substring(0,1)); String tmp = letters[p]; for(int i = 0; i < tmp.length(); i++){ for(int j = 0; j < next.size(); j++){ res.add(tmp.substring(i, i+1).concat(next.get(j))); } } return res; } }
非递归:
public class Solution { public String[] letters = {"0", "1", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"}; public List<String> letterCombinations(String digits) { int len = digits.length(); List<String> res = new ArrayList<String>(); res.add(""); for(int i = 0; i < len; i++){ int p = Integer.parseInt(digits.substring(i,i+1)); String tmp = letters[p]; List<String> single = new ArrayList<String>(); for(int j = 0; j < res.size(); j++){ for(int k = 0; k < tmp.length(); k++){ single.add(res.get(j).concat(tmp.substring(k,k+1))); } } res = single; } return res; } }
代码缩进有点问题,以后改正。
突然发现递归比非递归快一点,嗯。