Java - Permutation of ArrayList elements (Integer) - Can't get it to work properly

后端 未结 2 636
说谎
说谎 2020-12-19 19:05

I\'ve been looking around quite a bit to solve my issue. I got many problems solved but this one is still haunting me :S It\'s been a long time I haven\'t touch Java program

2条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-19 19:49

    You can try Recursion to solve this issue:

    public static void printPermutations(int[] n, int[] Nr, int idx) {
        if (idx == n.length) {  //stop condition for the recursion [base clause]
            System.out.println(Arrays.toString(n));
            return;
        }
        for (int i = 0; i <= Nr[idx]; i++) { 
            n[idx] = i;
            printPermutations(n, Nr, idx+1); //recursive invokation, for next elements
        }
    }
    

    More info can be had from this link: Combinatorics: generate all “states” - array combinations

    You can replicate the same logic here as well.

提交回复
热议问题