動態(tài)控制循環(huán)層數(shù) 如:函數(shù) cycle(int t) public void cycle(int t) { for(int i=1;i<4;i++) { for(int j=i+1;j<4;j++) { for(int k=j+1;k<4;k++) { ....含t層for循環(huán) } } } }
public class CycleTest { public static int count = 0; public static void main(String[] args) { dymaticCyc(3); System.out.println("count: "+ count); } public static void dymaticCyc(int num) { if(num > 0) { for(int i=1; i<=4; i++) { if(num == 1) { System.out.println("i: " + i); count++; } dymaticCyc(num-1); } } } }
排列組合算法
public class CycleTest1 { public static int count = 0; public static void main(String[] args) { //dymaticCyc(3,0,5); //System.out.println("count: "+ count); comb(5, 3,new int[60],0); //System.out.println("count: "+ count1); } public static void comb(int n, int m, int buff[],int count1) { if(m == 0)//遞歸結(jié)束,輸出 { for(int i=0; i<count1; i++) { System.out.print(buff[i]); } System.out.println(); return; } for(int i=0; i<=n-m; i++) { buff[count1++] = n-i; comb(n-i-1, m-1, buff,count1); --count1; } } public static void dymaticCyc(int num,int m,int sum) { //從sum個數(shù)中選num個數(shù) //dymaticCyc(2,0);此方法調(diào)用,m得從0開始 if(num > 0) { for(int i=1+m; i<=sum; i++) { dymaticCyc(num-1,i,sum); if(num == 1) { System.out.println(" m: " +m+ " i: " + i); count++; } } } } }
|