Java处理排列组合问题可以使用递归算法。
举例:中日各有5个乒乓球运动员。中方的战斗力分别为:100、98 、96、96、94、92. 日本的运动员战斗力分别为99、97、95、93 、91 问:中方固定顺序,日方打乱顺序,有多少种组合,分别是什么? 各种组合情况下哪个队赢?
这个题目和经典的题目田忌赛马是一样的,但是因为田忌赛马的数量太少,不容易看出效果。
直接上代码。
首先定义队员类:
class Member { String team; int value; String name; @Override public String toString() { return "Member{" + "team='" + team + '\'' + ", value=" + value + ", name='" + name + '\'' + '}'; } public Member(String team, int value, String name) { this.team = team; this.value = value; this.name = name; } }
编写递归函数
/** * * @param xiaoriList 日本队 * @param chinaList 中国队 * @param okList 每次排列已经选好日本队前几名队员 */ static private void myArrayge(List<Member>xiaoriList, List<Member> chinaList, List<Member> okList){ if (okList.size()==xiaoriList.size()){ ++cnt; int sorce=0; for (int i = 0; i < okList.size(); i++) { Member chinaMember = chinaList.get(i); Member xiaoribenMember = okList.get(i); System.out.println(chinaMember.team + " " + chinaMember.name + " : " + xiaoribenMember.team + " " + xiaoribenMember.name); sorce += chinaMember.value>xiaoribenMember.value ? 1:-1; } System.out.println("第" + cnt + "中组合 : 》》 " + (sorce>0 ? "中国万岁!!" : " 小日本侥幸了") ); }else{ for (int i = 0; i < xiaoriList.size() ; i++) { Member member = xiaoriList.get(i); if (okList.contains(member)) continue; okList.add(member); myArrayge(xiaoriList, chinaList,okList); okList.remove(member); } } }
编写主函数测试
public static void main(String[] args){ List<Member> xiaoriList = new ArrayList<Member>(); xiaoriList.add(new Member("日本" ,99,"甲")); xiaoriList.add(new Member("日本" ,97,"乙")); xiaoriList.add(new Member("日本" ,95,"丙")); xiaoriList.add(new Member("日本" ,93,"丁")); xiaoriList.add(new Member("日本" ,91,"戊")); List<Member> chinaList = new ArrayList<Member>(); chinaList.add(new Member("中国" ,100,"A")); chinaList.add(new Member("中国" ,98,"B")); chinaList.add(new Member("中国" ,96,"C")); chinaList.add(new Member("中国" ,94,"D")); chinaList.add(new Member("中国" ,92,"E")); List<Member> mySelectedList = new ArrayList<Member>(); myArrayge(xiaoriList, chinaList, mySelectedList); //System.out.println(cnt); }