递归-算法题1

137 阅读1分钟

17.Letter Combinations of a Phone Number

    给出一个数字字符串,返回这个数字字符串能表示的所有字母组合。如,对数字字符串“23”,返回:["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"];给出一个数字字符串,返回这个数字字符串能表示的所有字母组合。
    - 字符串的合法性;
    - 空字符串
    - 多个解的顺序

image

  • 思路:查看上边的树形图。
  • 代码:
package leetcode;

import java.util.LinkedList;
import java.util.List;

public class LetterCombinations {
    public static void main(String[] args){
        System.out.println(letterCombinations("236"));
    }
    //                               0   1     2      3      4      5      6      7       8      9
    private static String[] table = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
    private static List<String> letterCombinations(String digits){
        List<String> res = new LinkedList<>();
        if(digits.length() == 0)    
			return res;
        //寻找所有可能性
        dfs(0, "", digits.length() - 1, digits, res);
        return res;
    }

    /**
     * 递归寻找所有可能性
     * @param step 当前步数
     * @param s 临时结果
     * @param max 最大步数
     * @param digits 输入的字符串
     * @param res 最终的结果
     */
    private static void dfs(int step, String s, int max, String digits, List<String> res){
        //当前步数大于最大步数
        if(step > max){
            String temp = s;
            res.add(temp);
            return;
        }
        //字符串中的当前步数对应的字符的数字
        int num = digits.charAt(step) - '0';
        //遍历
        for(int i = 0; i < table[num].length(); ++i)    
			dfs(step + 1, s + table[num].charAt(i), max, digits, res);
    }
}