电话号码对应英语单词
问题描述
分析与解法
详细代码如下:
1 package chapter3jiegouzhifa.TelephoneMapWords; 2 /** 3 * 电话号码对应英语单词 4 * @author DELL 5 * 6 */ 7 public class TelephoneMapWords1 { 8 private int telLength; //电话号码的位数 9 private char c[][]={ //各个数字所能代表的字符 10 "".toCharArray(), //0 11 "".toCharArray(), //1 12 "ABC".toCharArray(), //2 13 "DEF".toCharArray(), //3 14 "GHI".toCharArray(), //4 15 "JKL".toCharArray(), //5 16 "MNO".toCharArray(), //6 17 "PQRS".toCharArray(), //7 18 "TUV".toCharArray(), //8 19 "WXYZ".toCharArray(), //9 20 }; 21 private int total[]={0,0,3,3,3,3,3,4,3,4}; //每个数字所能代表的字符数 22 private int number[]; //电话号码 23 private int answer[]; //数字目前所代表的字符在其所能代表的字符集中的位置 24 //构造函数 25 public TelephoneMapWords1(int number[]){ 26 this.number = number; 27 this.telLength = number.length; 28 answer = new int[telLength]; 29 } 30 //输出电话号码对应英语单词 31 public void output(){ 32 while(true){ 33 for(int i=0;i<telLength;i++) 34 System.out.print(c[number[i]][answer[i]]); 35 System.out.println(); 36 int k = telLength - 1; 37 while(k>=0){ 38 if(answer[k]<total[number[k]]-1){ 39 answer[k]++; 40 break; 41 }else{ 42 answer[k]=0; 43 k--; 44 } 45 } 46 if(k<0) 47 break; 48 } 49 } 50 public static void main(String[] args) { 51 int number[]={2,6,6,7,8,8,3,7}; 52 TelephoneMapWords1 tmw = new TelephoneMapWords1(number); 53 tmw.output(); 54 55 } 56 57 }
【问题1的解法二】递归方法
其实可以从循环算法中的n个for循环方法中得到提示,每层for循环,其实可以看成一个递归函数的调用。具体代码如下:
1 package chapter3jiegouzhifa.TelephoneMapWords; 2 /** 3 * 电话号码对应英语单词 4 * 【解法二】递归方法 5 * @author DELL 6 * 7 */ 8 public class TelephoneMapWords2 { 9 private int telLength; //电话号码的位数 10 private char c[][]={ //各个数字所能代表的字符 11 "".toCharArray(), //0 12 "".toCharArray(), //1 13 "ABC".toCharArray(), //2 14 "DEF".toCharArray(), //3 15 "GHI".toCharArray(), //4 16 "JKL".toCharArray(), //5 17 "MNO".toCharArray(), //6 18 "PQRS".toCharArray(), //7 19 "TUV".toCharArray(), //8 20 "WXYZ".toCharArray(), //9 21 }; 22 private int total[]={0,0,3,3,3,3,3,4,3,4}; //每个数字所能代表的字符数 23 private int number[]; //电话号码 24 private int answer[]; //数字目前所代表的字符在其所能代表的字符集中的位置 25 //构造函数 26 public TelephoneMapWords2(int number[]){ 27 this.number = number; 28 this.telLength = number.length; 29 answer = new int[telLength]; 30 } 31 //输出电话号码对应英语单词 32 public void output(int index){ 33 if(index==telLength){ 34 for(int i=0;i<telLength;i++) 35 System.out.print(c[number[i]][answer[i]]); 36 System.out.println(); 37 return; 38 } 39 for(answer[index]=0;answer[index]<total[number[index]];answer[index]++){ 40 output(index+1); 41 } 42 } 43 public static void main(String[] args) { 44 int number[]={2,6,6,7,8,8,3,7}; 45 TelephoneMapWords2 tmw = new TelephoneMapWords2(number); 46 tmw.output(0); 47 48 } 49 50 }
时间: 2024-11-05 01:43:33