DFS做法, 能满足需求,有改进的地方欢迎大家提出
import java.util.*;
//Author: Zhenjie Hao
public class Main {
public static void main(String[] args){
int input = 123;
List<List<String>> result = new ArrayList<>();
result = converse(input);
display(result);
}
public static List<List<String>> converse(int input){
String str = String.valueOf(input);
List<List<String>> result = new ArrayList<>();
dfs(str, 0 , new ArrayList<>(), result);
return result;
}
public static void dfs(String str, int startIndex, List<String> path, List<List<String>> result){
if(startIndex == str.length()){
result.add(new ArrayList<String>(path));
}
for(int i = startIndex + 1; i <= str.length(); i++){
String sub = str.substring(startIndex, i);
if(!isValid(sub)){
break;
}
path.add(numToAlg(sub));
dfs(str, i, path, result);
path.remove(path.size()-1);
}
}
public static boolean isValid(String str){
//str = "12" or "27"
if(str.charAt(0) == '0'){
return false;
}
int num = Integer.parseInt(str);
if(num < 1 || num > 26){
return false;
}
return true;
}
public static String numToAlg(String str){
//str = "12"
//putput = "d"
int num = Integer.parseInt(str);
return String.valueOf((char)('a' + num - 1));
}
public static void display(List<List<String>> result){
for(int i = 0; i < result.size(); i++){
StringBuilder sb = new StringBuilder();
for(int j = 0; j < result.get(i).size(); j++){
sb.append(result.get(i).get(j));
}
System.out.println(sb.toString());
}
}
}