アルゴリズム質問バンク002

/ **
*これはleetcodeに関する質問です。電話キーの数字に対応する文字によると、任意の2つの数字キーの可能な文字の組み合わせを返します。
例:
input:String "23" and
return:[" ad "、" ae "、" af "、" bd "、" be "、" bf "、" cd "、" ce "、" cf "]
* /

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

/**
 * 分析:思路一,我们进行遍历,采用
 */
public class Algorithm002 {
    //先定义初始化的数组
    private static char[][] dict = { {},{ 'a', 'b', 'c' }, { 'd', 'e', 'f' }, { 'g', 'h', 'i' }, { 'j', 'k', 'l' }, { 'm', 'n', 'o' },
            { 'p', 'q', 'r', 's' }, { 't', 'u', 'v' }, { 'w', 'x', 'y', 'z' } };

    public static List<String> letterCombinations(String nums){
        LinkedList<String> results = new LinkedList<>();
        if(nums.length()==0){
           return results;
        }else{
            addNumber(results,0," ",nums);
        }
        return results;
    }

    public static void addNumber(List<String> list, int i, String curstr, String digits)
    {
        if (i == digits.length()) {
            list.add(curstr);
            return;
        }
        char[] candidates = dict[digits.charAt(i) - '1'];
        for (char c : candidates)
            addNumber(list, i+1, curstr + c, digits);
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String str = scanner.next();
        List<String> list =letterCombinations(str);
        for (String sss:list) {
            System.out.println("字符串"+sss);
        }
    }
}

実際のテスト結果は次のとおりです。

45
字符串 gj
字符串 gk
字符串 gl
字符串 hj
字符串 hk
字符串 hl
字符串 ij
字符串 ik
字符串 il

 

おすすめ

転載: blog.csdn.net/LB_Captain/article/details/113915624