编程之美--电话号码匹配
来源:互联网 发布:中佛罗里达大学 知乎 编辑:程序博客网 时间:2024/05/14 12:26
package structure;public class TelNumber { /** * 给你一个电话号码,显示出该电话号码可以组成的所有单词 */ static String[] s = { "", // 0 "", // 1 0 1 上面都没有字母 "abc", // 2 "def", // 3 "ghi", // 4 "jkl", // 5 "mno", // 6 "pqrs", // 7 "tuv", // 8 "wxyz" // 9 }; static int[] total = { 0, 0, 3, 3, 3, 3, 3, 4, 3, 4 }; static int[] ans = new int[3]; static int[] tel = { 2, 3, 5 }; public static void main(String args[]) {int n = 3; // 电话有三位/*// 此种遍历 i j k 可以换成 一个数组for (int i = 0; i < s[2].length(); i++) for (int j = 0; j < s[3].length(); j++)for (int k = 0; k < s[5].length(); k++) { System.out.printf("%c%c%c", s[2].charAt(i), s[3].charAt(j), s[5].charAt(k)); System.out.println();}// 使用二种遍历for(ans[0] = 0;ans[0]<total[tel[0]];ans[0]++) for(ans[1]=0;ans[1]<total[tel[1]];ans[1]++)for(ans[2]=0;ans[2]<total[tel[2]];ans[2]++){ for(int i=0;i<3;i++)System.out.print(s[tel[i]].charAt(ans[i])); System.out.println();}*/back(0); } /** * 就是搜索一个棵树,而且树的结点扩展都知道,也就是 s[i]所表示的字符串都为扩展结点 * 而我们可以另开辟一个数组来记录当前的值,最后进行输出,但下面的例子不是这样的 * ans[i] 表示第 i 个电话号码 所表示的字母中的第 j位位置,也就是 第i 个结点所能扩展的位置 * 这样在最后就能记录出当前一条的记录 * @param t */ static void back(int t){if(t == tel.length){ for(int i =0;i<t;i++)System.out.printf("%c",s[tel[i]].charAt(ans[i])); System.out.println(); return;}for(ans[t]=0;ans[t]<total[tel[t]];ans[t]++){ back(t+1);} }}