题目:如果甲组有队员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/