用1、2、2、3、4、5这六个数字,用java写一个main函数,打印出所有不同的排列

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;

/**
 * 项目名称:本示例作者站在方法复用、解构的角度来写的,按照数据整理,数据过滤,数据清洗的逻辑来做的,
 * 			如果仅仅是为了效率,可以把业务逻辑都放到 recursion 方法里
 * 类名称:RecursionDemo.java 
 * 类描述: 
 * 创建人:beyond 
 * 创建时间:2016年10月27日 下午10:17:27 
 * 修改人: 
 * 修改时间: 
 * 修改备注: 
 * @version
 */
public class RecursionDemo {
	 public static void main(String[] args) {  
	        List<Integer> data = new LinkedList<>();  
	        data.add(1);
	        data.add(2);  
	        data.add(2);  
	        data.add(3);
	        data.add(4);
	        data.add(5);
	          
//	  		 全排列
	        List<List<Integer>> result = recursion(data);  
//	  		去除2重复的数据
	        Set<List<Integer>> resultSet = new HashSet<>(result);
//	  		各集合参数都为List,方便复用
	        result = new ArrayList<>(resultSet);
//	       	剔除集合里“4”在第三位,“3”与“5”相连的元素
	        clean(result);
//	       	 结果为198
	        System.err.println(result.size());
	        
	 }  
	 
	 /**
	  * @description: 全排列
	  * 	1. 如果集合长度为 1 ,则将该集合放入List集合,否则走下面逻辑;
	  * 	2. 取集合第一个元素,剔除第一个元素后组装新的集合,递归;
	  * 	3. 新建List<List<>>集合,递归返回结果放入该集合;
	  * 	4. 取得递归记过二次循环遍历,与2中集合第一个元素重新拼接组装;
	  * 
	  * @param source
	  * @return   
	  * @return List<List<Integer>>   
	  * @throws
	  * @author beyond
	  * @data:2016年10月27日下午9:27:02
	  */
	 public  static List<List<Integer>> recursion(List<Integer> source){
		 
		 List<List<Integer>> target = new ArrayList<>();

		 if(source.size() == 1){
			 target.add(source);
		 }else{
			 Integer first = source.get(0);
			 List<Integer> otherList = source.subList(1, source.size());
			 
//			 递归直到otherList里含一个元素
			 List<List<Integer>> tmpList = recursion(otherList);
			 
			 for(List<Integer> tmp : tmpList){
				 for(int i=0 ; i<= tmp.size() ; i++){
					 List<Integer> innerList = new ArrayList<Integer>(tmp);
					 innerList.add(i,first);
					 target.add(innerList);
				 }
			 }
		 }
		 
		 return target;
	 }
	 
	 /**
	  * @description: 剔除集合里“4”在第三位,“3”与“5”相连的元素
	  * @param source   
	  * @return void   
	  * @throws
	  * @author beyond
	  * @data:2016年10月27日下午10:12:10
	  */
	 public  static void clean(List<List<Integer>> source){
		
		 for(int i=0 ; i<source.size() ; i++){
			 List<Integer> tmpList = source.get(i);
			 int size = tmpList.size();
			 if(size > 2){
				 if(tmpList.get(2).equals(4)){
					 source.remove(i);
					 i--;
					 continue;
				 }
			 }
			 
			 for(int j=size-1 ; j>0 ; j--){
				 if(tmpList.get(j).equals(3) && tmpList.get(j-1).equals(5)){
					 source.remove(i);
					 i--;
					 continue;
				 }else if(tmpList.get(j).equals(5) && tmpList.get(j-1).equals(3)){
					 source.remove(i);
					 i--;
					 continue;
				 }
			 }
		 }
		 
	 }
}

猜你喜欢

转载自bugyun.iteye.com/blog/2333781