Java 使用hashmap的递归

Java 使用hashmap的递归,java,recursion,numbers,hashmap,int,Java,Recursion,Numbers,Hashmap,Int,我有一个数组,它有以下数字 int[] arr = {2,4,3,1,5,6,0,7,8,9,10,11,12,13,14,15}; 或任何其他关于这件事的命令。 我需要使用递归对这些数字进行所有可能的组合,但要满足一个条件,即下一个与当前数字组合的数字只能来自hashmap给出的特定数字: 当递归取1时,下一个数字可以来自{0,4,5,2,6}(来自HaspMap),如果我取10,下一个数字可以来自{1,4,5},依此类推 static HashMap<Integer,Integer[

我有一个数组,它有以下数字

int[] arr = {2,4,3,1,5,6,0,7,8,9,10,11,12,13,14,15};
或任何其他关于这件事的命令。 我需要使用递归对这些数字进行所有可能的组合,但要满足一个条件,即下一个与当前数字组合的数字只能来自hashmap给出的特定数字: 当递归取1时,下一个数字可以来自{0,4,5,2,6}(来自HaspMap),如果我取10,下一个数字可以来自{1,4,5},依此类推

static HashMap<Integer,Integer[]> possibleSeq = new HashMap<Integer,Integer[] >();
private static void initialize(HashMap<Integer,Integer[]> possibleSeq) {
    possibleSeq.put(0,new Integer[]{1,4,5});
    possibleSeq.put(1,new Integer[]{0,4,5,2,6});
    possibleSeq.put(2,new Integer[]{1,3,5,6,7});
    possibleSeq.put(3,new Integer[]{2,6,7});
    possibleSeq.put(4,new Integer[]{0,1,5,8,9});
    possibleSeq.put(5,new Integer[]{0,1,2,4,6,8,9,10});
    possibleSeq.put(6,new Integer[]{1,2,3,5,7,9,10,11});
    possibleSeq.put(7,new Integer[]{2,3,6,10,11});
    possibleSeq.put(8,new Integer[]{9,4,5,12,13});
    possibleSeq.put(9,new Integer[]{10,4,5,8,6,12,13,14});
    possibleSeq.put(10,new Integer[]{7,6,5,9,11,15,13,14});
    possibleSeq.put(11,new Integer[]{6,7,10,14,15});
    possibleSeq.put(12,new Integer[]{8,9,13});
    possibleSeq.put(13,new Integer[]{8,9,10,12,14});
    possibleSeq.put(14,new Integer[]{9,10,11,13,15});
    possibleSeq.put(15,new Integer[]{10,11,14});    
}
static HashMap possibleSeq=new HashMap();
私有静态void初始化(HashMap可能seq){
possibleSeq.put(0,新整数[]{1,4,5});
possibleSeq.put(1,新整数[]{0,4,5,2,6});
possibleSeq.put(2,新整数[]{1,3,5,6,7});
possibleSeq.put(3,新整数[]{2,6,7});
possibleSeq.put(4,新整数[]{0,1,5,8,9});
possibleSeq.put(5,新整数[]{0,1,2,4,6,8,9,10});
possibleSeq.put(6,新整数[]{1,2,3,5,7,9,10,11});
possibleSeq.put(7,新整数[]{2,3,6,10,11});
possibleSeq.put(8,新整数[]{9,4,5,12,13});
possibleSeq.put(9,新整数[]{10,4,5,8,6,12,13,14});
possibleSeq.put(10,新整数[]{7,6,5,9,11,15,13,14});
possibleSeq.put(11,新整数[]{6,7,10,14,15});
possibleSeq.put(12,新整数[]{8,9,13});
possibleSeq.put(13,新整数[]{8,9,10,12,14});
possibleSeq.put(14,新整数[]{9,10,11,13,15});
possibleSeq.put(15,新整数[]{10,11,14});
}
注:我需要把所有可能的数字从数字长度1到10开始。
救命啊

对于初学者,可以尝试以下方法:

void findPath(Set paths, Stack path, int[] nextSteps, Set numbersLeft) {
    if (numbersLeft.isEmpty()) {
        //Done
        paths.add(new ArrayList(path));
        return;
    }

    for (int step:nextSteps) {
        if (numbersLeft.contains(step)) {
            // We can move on
            path.push(step);
            numbersLeft.remove(step);
            findPath(paths, path, possiblePaths.get(step), numbersLeft);
            numbersLeft.add(path.pop());
        }
    }       
}
起始值应该是一个空集合、空堆栈、一个与初始数组相同的下一步,以及一个从初始数组创建的集合。当返回时,应使用可能的路径填充路径集

我还没有测试过这个,这里有bug和更优雅的解决方案