Permutation of array

后端 未结 11 1225
我寻月下人不归
我寻月下人不归 2020-11-22 07:56

For example I have this array:

int a[] = new int[]{3,4,6,2,1};

I need list of all permutations such that if one is like this, {3,2,1

11条回答
  •  梦谈多话
    2020-11-22 08:28

    Implementation via recursion (dynamic programming), in Java, with test case (TestNG).


    Code

    PrintPermutation.java

    import java.util.Arrays;
    
    /**
     * Print permutation of n elements.
     * 
     * @author eric
     * @date Oct 13, 2018 12:28:10 PM
     */
    public class PrintPermutation {
        /**
         * Print permutation of array elements.
         * 
         * @param arr
         * @return count of permutation,
         */
        public static int permutation(int arr[]) {
            return permutation(arr, 0);
        }
    
        /**
         * Print permutation of part of array elements.
         * 
         * @param arr
         * @param n
         *            start index in array,
         * @return count of permutation,
         */
        private static int permutation(int arr[], int n) {
            int counter = 0;
            for (int i = n; i < arr.length; i++) {
                swapArrEle(arr, i, n);
                counter += permutation(arr, n + 1);
                swapArrEle(arr, n, i);
            }
            if (n == arr.length - 1) {
                counter++;
                System.out.println(Arrays.toString(arr));
            }
    
            return counter;
        }
    
        /**
         * swap 2 elements in array,
         * 
         * @param arr
         * @param i
         * @param k
         */
        private static void swapArrEle(int arr[], int i, int k) {
            int tmp = arr[i];
            arr[i] = arr[k];
            arr[k] = tmp;
        }
    }
    

    PrintPermutationTest.java (test case via TestNG)

    import org.testng.Assert;
    import org.testng.annotations.Test;
    
    /**
     * PrintPermutation test.
     * 
     * @author eric
     * @date Oct 14, 2018 3:02:23 AM
     */
    public class PrintPermutationTest {
        @Test
        public void test() {
            int arr[] = new int[] { 0, 1, 2, 3 };
            Assert.assertEquals(PrintPermutation.permutation(arr), 24);
    
            int arrSingle[] = new int[] { 0 };
            Assert.assertEquals(PrintPermutation.permutation(arrSingle), 1);
    
            int arrEmpty[] = new int[] {};
            Assert.assertEquals(PrintPermutation.permutation(arrEmpty), 0);
        }
    }
    

提交回复
热议问题