Java的全排列模板

c++有全排列函数,我们Java没有,所以我们只能自己手写了。

模板一:(不去重)

import java.util.ArrayList;
import java.util.Random;
import java.util.Scanner;
public class liyunpeng {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        int[] a = {1, 2, 3, 4};
         sum(a,0,a.length);
    }
public static void sum(int[] a, int start, int end ) {
        int b, c, d;
        if (start == end-1) {
        for (b = 0; b < end; b++) {
        System.out.print(a[b]);
        }
        System.out.println();
        return;
        }
        for (c = start; c < end; c++) {
        swap(a, c, start);
        sum( a, start +1, end);
        swap(a,c,start);
        }
        }
public static void swap ( int[] c, int a, int b){
        int d = c[a];
        c[a] = c[b];
        c[b] = d;
        }
        }

模板二:使用hashset来帮助我们去重

import java.util.*;

public class liyunpeng {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);

        int[] a = {1, 9, 9, 4};
        sum(a,0,a.length);
        System.out.println(s.size());
         int f;
        int[] b = s.stream().mapToInt(Integer::intValue).toArray();
        for(int e=0;eb[f]){
                    swap(b,e,f);
                }
            }
        }
        for(f=0;f s=new HashSet<>();

public static void sum(int[] a, int start, int end) {
        int b, c, d;
        int[] o=new int[50000];
        if (start == end-1) {
        int g=jisuan(a);
        if(sushu(g)==1){
        s.add(g);

        }
        return;
        }
        for (c = start; c < end; c++) {
        swap(a, c, start);
        sum( a, start +1, end);
        swap(a,c,start);
        }

        }
public static void swap ( int[] c, int a, int b){
        int d = c[a];
        c[a] = c[b];
        c[b] = d;
        }
public static int jisuan(int[] a){
        int b;
        b=a[0]*1000+a[1]*100+a[2]*10+a[3];
        return b;
        }
public static int sushu(int a){
        if(a<2||a==4)
        return 0;
        if(a==2||a==3)
        return 1;
        if(a%6!=5&&a%6!=1)
        return 0;
        for(int b=5;b*b<=a;b=b+6){
        if(a%b==0||a%(b+2)==0)
        return 0;
        }
        return 1;
        }

        }
*/

你可能感兴趣的:(算法模板,java,深度优先,全排列)