排列组合DFS(java)

package lanqiao;

public class PermutationsAndCombinateions {

    static int n=5,m=3;//n是有5个1-5的数,m代表从中选择3个
    static int a[]=new int[n];
    static int v[]=new int[n];
    static int b[]=new int[n];
    static int num=0;
    public static void main(String[] args) {
        for(int i=0;i1;
            b[i]=i+1;
        }
        //fun1(0);
        fun2(0);
        //fun3(0,0);
    }

    //每个空位有n中选法,共有n的n次方种
    public static void fun1(int d){
        if(d==a.length){
            for(int i=0;iout.printf("%4d",b[i]);
            }
            num++;
            System.out.println("  "+num);
            return;
        }
        for(int i=0;i1);
        }
    }   
    //n个数全排列  n!
    public static void fun2(int d){
        if(d==a.length){
                for(int i=0;iout.printf("%4d",b[i]);
                }   
                num++;
                System.out.println("  "+num);

            return;
        }
        for(int i=d;i1;
            fun2(d+1);

        }
    }
    //从n个数中选择m种
    public static void fun3(int d,int cnt){
        if(cnt==m){
            for(int i=0;iout.printf("%4d",b[i]);
            }   
            num++;
            System.out.println("  "+num);
            return;
        }
        for(int i=d;i1,cnt+1);
        }

    }

}

你可能感兴趣的:(dfs)