当前位置:网站首页>Backtracking / solution space tree permutation tree

Backtracking / solution space tree permutation tree

2022-06-11 14:42:00 xcrj

 Insert picture description here

  • Initially select the No 0 Index node
  • Select the first i Parent node formed after elements , The child node of the parent node , Through the parent node i And the j Element exchange , Take turns to j Put the first element in the second i position , Form child nodes
package xcrj.kchalgorithm.backtracking;

import java.util.Arrays;

/** *  Permutation tree  *  Achieve the required arrangement , All the elements are in ; Put that element in the 1 position , Put that element in the 2 position , By analogy  * <p> *  Select the first i Parent node formed after elements , The child node of the parent node , Through the parent node i And the j Element exchange , Take turns to j Put the first element in the second i position , Form child nodes  */
public class PermutationTree {
    
    /** * @param xs * @param i * @param len */
    public static void permutationTree(int[] xs, int i, int len) {
    
        //  Reach the leaf node output 
        if (i == len) {
    
            System.out.println(Arrays.toString(xs));
        }
        //  Reach the non leaf node , Generate i All child nodes of the node j
        else {
    
            // ! Select the first i Parent node formed after elements , The child node of the parent node , Through the parent node i And the j Element exchange , Take turns to j Put the first element in the second i position , Form child nodes 
            for (int j = i; j < len; j++) {
    
                //  In exchange for , Through the parent node i And the j Element exchange , Take turns to j Put the first element in the second i position , Form child nodes 
                int temp = xs[j];
                xs[j] = xs[i];
                xs[i] = temp;
                //  Depth first traversal operation child node 
                permutationTree(xs, i + 1, len);
                //  Exchange back 
                int temp2 = xs[j];
                xs[j] = xs[i];
                xs[i] = temp2;
            }
        }
    }

    public static void main(String[] args) {
    
        int[] xs = {
    1, 2, 3};
        permutationTree(xs, 0, xs.length);
    }
}

原网站

版权声明
本文为[xcrj]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/162/202206111426194967.html