分治法,数组全排序

题目:如果甲组有队员a, b, c; 乙组有队员x, y, z; a不会对上x,c不会对上y或者z; 求可能的对战情况。

package mytest;

/**
 * 对战情况
 * @author ephuizi
 *
 */
public class Solution {
	int line ;
	int row = 2 ;
	char[][] solution ;
	public Solution(char[] a, char[] b){
		this.line = a.length;
		this.solution = new char[line][row];
		for(int i=0; i<line; i++){
			this.solution[i][0] = a[i];
			this.solution[i][1] = b[i];
		}
	};
	public void print(){
		for(int i = 0;i<line; i++){
			for(int j=0; j<row; j++)
				System.out.print(this.solution[i][j]);
			System.out.print("| ");
		}
	};
}

package mytest;
/**
 * 数组全排序
 * @author ephuizi
 *
 */
public class TotalOrder {
	char[] first;
	char[] order;
	public TotalOrder(char[] first, char[] order){
		this.first = first;
		this.order = order;
	}
	/*
	 * 分治法
	 * 假设数组含有n个元素,则提取数组中的每一个元素做一次头元素,
	 * 然后全排列除数组中除第一个元素之外的所有元素,这样就达到了对数组中所有元素进行全排列的得目的。
	 * 把数组无限缩小(不断调用函数自身)反复运用上述思想,则实现了全排列。
	 * 注意:一次循环过后,数组又返回原来的样子(这是相对的,注意理解,可以以当n为3时进行跟踪程序,这样就很容易理解了)
	 * */
	public void getTotalOrder(int begin, int end){
		if(begin == end){
			Solution s = new Solution(first, order);
			if(s.solution[0][1]!='x'&&s.solution[2][1]!='y'
					&&s.solution[2][1]!='z'){
				System.out.print("可能的对战: ");
				s.print();
				System.out.println();	
			}
			return;
		}else{
			for(int i = begin; i <= end; i++){
				this.swap(begin, i);
				getTotalOrder(begin+1, end);
				this.swap(i, begin);//还原数组
			}
		}
		
	}
	//交换元素
	public void swap(int from, int to){
		if(order[from] == order[to])
			return;
		char temp = order[to];
		order[to] = order[from];
		order[from] = temp;
	}
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		char[] a = {'a', 'b', 'c'};
		char[] b = {'x','y','z'};
		TotalOrder t = new TotalOrder(a, b);
		t.getTotalOrder(0, b.length-1);
	}
}


参考:http://blog.163.com/blue_boy29/blog/static/76212945200971093732817/







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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值