递归算法总结java版

1、给出一个数据A={a ,b ,c} (其中个数可变),打印出该元素的所有组合。

    因为题目要求n可变,所以不可能是n层for循环的方式,可以采用递归的方式来实现,       每次取一个元素,在剩下元素的数组中递归,要注意递归结束的条件。

     

package com.zy;
public class AllCombination {
	public static void main(String[] args) {  
        char buf[]={'a','b','c'};  
        perm(buf,0,buf.length-1);  
    }  
	public static boolean isRepeat(char[] buf,int start,int end){
		for(int i=start;i<end;i++){
			if(buf[i]==buf[end]){
				return false;
			}
		}
		return true;
	}
    public static void perm(char[] buf,int start,int end){  
        if(start==end){//当只要求对数组中一个字母进行全排列时,只要就按该数组输出即可  
            for(int i=0;i<=end;i++){  
                System.out.print(buf[i]);  
            }  
            System.out.println();     
        }  
        else{//多个字母全排列  
            for(int i=start;i<=end;i++){ 
            	if(isRepeat(buf,start,i)){
            		 char temp=buf[start];//交换数组第一个元素与后续的元素  
                     buf[start]=buf[i];  
                     buf[i]=temp;  
                        
                     perm(buf,start+1,end);//后续元素递归全排列  
                        
                     temp=buf[start];//将交换后的数组还原  
                     buf[start]=buf[i];  
                     buf[i]=temp;  
            	}
               
            }  
        }  
    }  
}

2.把 M 个同样的苹果放在N 个同样的盘子里,允许有的盘子空着不放,问共有多少

种不同的分法?(用K 表示)注意:5,1,1 和1,5,1 是同一种分法。

package com.zy;
import java.util.Scanner;
public class ApplePackage {
	public static void main(String args[]){
		int t,m,n;
		Scanner in=new Scanner(System.in);
		t=in.nextInt()+1;
		while(--t>0){
			m=in.nextInt();
			n=in.nextInt();
			System.out.println(packFun(m,n));
		}
	}
public static int packFun(int m,int n){//定义m个苹果放在n个篮子里
	if(m==0||n==1){
		return 1;
	}if(m<n){
		return packFun(m,m);
	}else{
		return packFun(m,n-1)+packFun(m-n,n);
	}
 }
}

3.java-输入一个字符串,输出该字符串中字符的所有组合。举个例子,如果输入abc,它的组合有a、b、c、ab、ac、bc、abc

<span style="font-size:18px;">import java.util.ArrayList;
import java.util.List;

public class Combination {

	public static void main(String[] args) {

		char[] a = { 'a', 'b', 'c' };
		List<Character> list = new ArrayList<Character>();
		for (int i = 1, len = a.length; i <= len; i++) {
			combine(a, 0, i, list);
		}
	}
        /*
	 * we can also use Stack like this:
	    stack.push(a[begin]);
		combination(a,begin+1,number-1,stack);
		stack.pop();
		combination(a,begin+1,number,stack);
	 */
	public static void combine(char[] a, int begin, int resultLength,List<Character> list) {
		
		if (resultLength == 0) {
			System.out.println(list.toString());
			return;
		}
		if (begin == a.length){
			return;
		}
		
		list.add(a[begin]);
		combine(a, begin + 1, resultLength - 1, list);
		list.remove((Character) a[begin]);
		combine(a, begin + 1, resultLength, list);
	}
}</span><span style="font-size:32px;">
</span>

4.中兴面试题 输入两个整数 n 和 m ,从数列 1 , 2 , 3.......n 中随意取几个数 , 使其和等于 m

<span style="font-weight: normal;">import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

public class CombinationToSum {

	/*
第21 题
2010 年中兴面试题
编程求解:
输入两个整数 n 和 m ,从数列 1 , 2 , 3.......n 中随意取几个数 ,
使其和等于 m , 要求将其中所有的可能组合列出来 .
	 * two solutions
	 * permutation01:Recursion.easy to write and read-->pick n or not,haha
	 * permutation02:put n,then put n-1...if bigger,remove;if smaller,keep putting;if ok,output.
	 */
	public static void main(String[] args) {
		CombinationToSum cts=new CombinationToSum();
		//permutation01(int sum,int n)
		cts.permutation01(10,10);
		System.out.println("===========");
		cts.permutation02(10,6);
	}

	/*Recursion.use Stack<Integer>
	we can use ArrayList,too.
	private List<Integer> list=new ArrayList<Integer>();
	list.add(n);
	list.remove(list.indexOf(n));
	*/
	private Stack<Integer> stack=new Stack<Integer>();
	public  void permutation01(int sum,int n){
		if(n<=0||sum<=0)return;
		if(sum==n){
			printStack(stack);
			System.out.print(n);
			System.out.println();
		}
		stack.add(n);
		permutation01(sum-n,n-1);
		stack.pop();
		permutation01(sum,n-1);
	}
	
	public  void permutation02(int sum, int n) {
		if(n<=0||sum<=0)return;
		for (int i = n; i > 0; i--) {
			if (i == sum) {
				System.out.println(i);
				continue;
			}
			List<Integer> list = new ArrayList<Integer>();
			list.add(i);
			for (int j = i - 1; j > 0;) {
				list.add(j);
				int ret = isOK(list, sum);
				if (ret < 0) {
					j--;
				}
				if (ret == 0) {
					printList(list);
					System.out.println();
					j = list.get(1) - 1;//now we go back and make the second element smaller
					list.clear();
					list.add(i);
				}
				if (ret > 0) {
					list.remove(list.size()-1);//too large,remove the last element
					j--;
				}
			}
		}
	}

	// whether the sum of list element equals to sum or not
	public static int isOK(List<Integer> list, int sum) {
		int re = 0;
		int total = 0;
		for (int each : list) {
			total += each;
		}
		if (total > sum)
			re = 1;
		if (total < sum)
			re = -1;
		return re;

	}

	public void printStack(Stack<Integer> stack){
		/*
		while(!stack.isEmpty()){
			int temp=stack.pop();
			System.out.print(temp+" ");
		}
		*/
		//don't remove the elements in stack
		for(Integer each:stack){
			System.out.print(each+" ");
		}
	}


	public  void printList(List<Integer> list) {
		for (int each : list) {
			System.out.print(each + " ");
		}
	}
	
}</span>




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值