【DFS】Letter Combinations of a Phone Number

来源:互联网 发布:手机永不休眠软件 编辑:程序博客网 时间:2024/06/01 22:09

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 class Solution {        public String[] ss = {"","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};        public ArrayList<String> res = new ArrayList<String>();        public void dfs(String digits, String str, int pos){        if(str.length() == digits.length()){            res.add(str);            return ;        }                    int t = Integer.parseInt("" + digits.charAt(pos));            String st = ss[t];            for(int j=0; j<st.length(); j++){                dfs(digits, str+st.charAt(j), pos+1);            }    }        public ArrayList<String> letterCombinations(String digits) {        dfs(digits, "", 0);        return res;    }}


0 0