编程之美3.2电话号码对应英语单词 java版

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package chart_3;

/**
 *
 * 3.2 电话号码对应英语单词
 */
public class NumberTel_3_2 {

    public static String[][] c = {{""}, {""}, {"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 int[] total = {0, 0, 3, 3, 3, 3, 3, 4, 3, 4};

    public static void main(String[] args) {

        int[] number = {2, 3, 4};
        int n = number.length;
        int[] answer = new int[n];
        //解法一 直接循环
        methord1(number, answer, n);
        System.out.println("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%");
        //解法二 递归调用
        methord2(number, answer, 0, n);

    }

    private static void methord1(int[] number, int[] answer, int n) {

        while (true) {
            for (int i = 0; i < n; i++) {
                System.out.print(c[number[i]][answer[i]]);
            }
            System.out.println();
            int k = n - 1;
            while (k >= 0) {
                if (answer[k] < total[number[k]] - 1) {
                    answer[k]++;
                    break;
                } else {
                    answer[k] = 0;
                    k--;
                }
            }
            if (k < 0) {
                break;
            }
        }
    }

    private static void methord2(int[] number, int[] answer, int index, int n) {
        if (index == n) {
            for (int i = 0; i < n; i++) 
                System.out.print(c[number[i]][answer[i]]);
                System.out.println();
                return;
        }
        for(answer[index] =0;answer[index]<total[number[index]];answer[index]++){
            methord2(number,answer,index+1,n);
        }
    }
}

    原文作者:哒宝甜
    原文地址: https://blog.csdn.net/tt285955925/article/details/52127856
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞