给定一个数列,比如1234,将它match到字母上,1是A,2是B等等,那么1234可以是
ABCD
但是还可以是12是L,所以1234也可以写作
LCD 或者
AWD
ABCD
但是还可以是12是L,所以1234也可以写作
LCD 或者
AWD
package string;
import java.util.*;
public class DecodeCombination {
// http://www.1point3acres.com/bbs/forum.php?mod=viewthread&tid=188433&extra=page%3D1%26filter%3Dsortid%26sortid%3D311%26searchoption%5B3046%5D%5Bvalue%5D%3D2%26searchoption%5B3046%5D%5Btype%5D%3Dradio%26sortid%3D311
public static void main(String[] args) {
List<String> strs = generateCombination("1234");
for (String str : strs) {
System.out.println(str);
}
//ABCD AWD LCD
}
public static List<String> generateCombination(String s) {
List<String> ret = new LinkedList<String>();
if (s == null || s.length() == 0) {
return ret;
}
String[] map = { "", "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" };
dfs(s, ret, 0, "", map);
return ret;
}
static void dfs(String s, List<String> ret, int index, String item, String[] map) {
if (index >= s.length()) {
ret.add(item);
return;
}
int i = s.charAt(index) - '0';
dfs(s, ret, index + 1, item + map[i], map);
// 如果可以有两位数,比如"24"就可以对应"X",就要继续递归。而"27"就没有的对应。
if (index < s.length() - 1) {
int j = s.charAt(index + 1) - '0';
if (i * 10 + j <= 26) {
dfs(s, ret, index + 2, item + map[i * 10 + j], map);
}
}
}
}