遞迴實現乘方,最簡單型別揹包問題,組合
阿新 • • 發佈:2018-12-07
import java.util.Scanner; /** * 遞迴實現乘方問題 * @author Administrator * */ public class Pow{ @SuppressWarnings("resource") public static void main(String[] args){ while(true) { System.out.println("Please enter x and y:"); Scanner s1 = new Scanner(System.in); int x = s1.nextInt(); int y = s1.nextInt(); System.out.println("The answer is:"+powing(x,y)+"\n"); } } public static int powing(int x,int y){ if(y==0) return 1; if(y==1) return x; if(y%2==1) return x*powing(x*x,y/2); return powing(x*x,y/2); } }
-
揹包問題
問題闡述:假設想要讓揹包精確地承重20磅,並且有 5 個可以放入的資料項,它們的重量分別是 11 磅,8 磅,7 磅,6 磅,5 磅。這個問題可能對於人類來說很簡單,我們大概就可以計算出 8 磅+ 7 磅 + 5 磅 = 20 磅。但是如果讓計算機來解決這個問題,就需要給計算機設定詳細的指令了。
實質問題:找出一連串的數字中等於某個特定值的所有組合
/** * 用遞迴解決揹包問題 * @author Administrator * 變相的組合,遍歷所有數字組合在一起,符合條件的列印 */ public class Baggage { private int[] bag; private boolean[] select;//記錄是否被選擇 public static int flag=-1; public Baggage(int[] bag) { this.bag = bag; select = new boolean[bag.length]; } public void Bag(int total,int index) { //總數<0:total減掉放進揹包裡的重量<0 (>0同理) if(total<0 || total>0 && index>=bag.length) return; //total==0,代表揹包重量等於起始重量,符合條件,列印 if(total==0) { for(int i=0;i<index;i++) { if(select[i]==true) System.out.print(bag[i]+" "); } System.out.println(); flag=1; return; } select[index] = true; Bag(total-bag[index],index+1); select[index] = false; Bag(total,index+1); } public static void main(String[] args) { int[] arr = {20,4,6,8,10}; int total = 20; Baggage b = new Baggage(arr); b.Bag(total, 0); if(flag==-1) System.out.println("sorry!"); } }
-
組合
問題闡述:將A B C D E五個元素任意三個進行組合,要求輸出所有組合情況
解析問題:A B C D E任意三個組合在一起,我們從五個中任意選出一個,那麼則剩下4個元素在裡頭,在四個元素我們要選出2個,於是我們又從4個元素裡面拿出1個,那麼則剩下3個元素在裡頭,我們有3種選擇,在三個元素我們要選出1個,於是我們又從3個元素裡面拿出1個,這樣子我們就完成了,我們倒回去,由於3個元素有3種選擇,我們把每一種選擇都選擇一遍以後,會到上一步即在剩下4個元素在裡頭選1個,重複與3選1類似的操作。
/** * 遞迴實現組合 * @author Administrator * */ public class Combination { private char[] com; private boolean[] select; public Combination(char[] com) { this.com = com; select = new boolean[com.length]; } public void combination(int theNumber,int index) { if(theNumber==0) { for(int i=0;i<index;i++) if(select[i]==true) System.out.print(com[i]+" "); System.out.println(); return; } if(index>=com.length) return; select[index] = true; //System.out.println("1111 theNumber="+theNumber+" index="+index); combination(theNumber-1,index+1); select[index]=false; //System.out.println("2222 theNumber="+theNumber+" index="+index); combination(theNumber,index+1); //System.out.println("3333 theNumber="+theNumber+" index="+index); } public static void main(String[] args) { char[] c = {'A','B','C','D','E'}; Combination k = new Combination(c); k.combination(3, 0); } }