递归实现乘方,最简单类型背包问题,组合

 

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);
	}
}

猜你喜欢

转载自blog.csdn.net/szlg510027010/article/details/83060772