当前位置:网站首页>Full Permutation V3 recursion of brute force method /1~n

Full Permutation V3 recursion of brute force method /1~n

2022-06-10 21:09:00 xcrj

package xcrj.kchalgorithm.bruteForce;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/** *  Input n *  give 1~n All permutations of  *  Power set problem ( Combination question ): Incremental greed , Increment without considering the order  *  The problem of permutation : Incremental greed , Consider the order of increment , The order is represented by the index  * <p> *  Incremental brute force method  * 1 * 12 | 21 * 123 312 132 | 321 231 213 * <p> *  recursive : *  Recursive export : The number to be added i> The maximum number n *  Recursive body : Give the original arrangement each time   Index based j increase i  produce 1 New permutations  */
public class FullPermutation3 {
    
    static Set<List<Integer>> setList = new HashSet<>(6);

    static {
    
        //  initialization , Insert empty collection 
        List<Integer> list = new ArrayList<>(1);
        setList.add(list);
    }

    /* stay setList Set List No j Position insert i*/
    public static void insertI(List<Integer> list, int i, Set<List<Integer>> setListTemp) {
    
        //  stay setList Set List No j Position insert i
        for (int j = 0; j < i; j++) {
    
            List<Integer> listTemp = new ArrayList<>(3);
            //  Deep copy list To listTemp
            for (Integer v : list) {
    
                listTemp.add(v);
            }
            listTemp.add(j, i);
            setListTemp.add(listTemp);
        }
    }

    public static void fullPermutation3(int i, int n) {
    
        if (i <= n) {
    
            Set<List<Integer>> setListTemp = new HashSet<>(6);
            for (List<Integer> list : setList) {
    
                insertI(list, i, setListTemp);
            }
            //  Deep copy setListTemp To setList
            setList.clear();
            for (List<Integer> listTemp : setListTemp) {
    
                List<Integer> list = new ArrayList<>(3);
                for (Integer v : listTemp) {
    
                    list.add(v);
                }
                setList.add(list);
            }
            //  add to i+1
            fullPermutation3(i + 1, n);
        }
    }

    public static void main(String[] args) {
    
        fullPermutation3(1, 3);
        System.out.println(setList);
    }
}

原网站

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