[Leetcode] Letter Combinations of a Phone Number (Java)

来源:互联网 发布:七分网络查分 编辑:程序博客网 时间:2024/06/04 19:17

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.

DFS

public class Solution {    private static final String[] number ={"abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};private ArrayList<String> res ;public ArrayList<String> letterCombinations(String digits) {res = new ArrayList<String>();print(digits, 0,"");if(res.size()==0)res.add("");return res;}private void print(String digits,int index,String s) {if(index==digits.length()) {res.add(s);return;}for(int i=0;i<number[digits.charAt(index)-'2'].length();i++){s+=(number[digits.charAt(index)-'2'].charAt(i));print(digits, index+1,s);s =s.substring(0,s.length()-1);}}}


0 0
原创粉丝点击