题目: 用1 2 2 3 4 5 这六个数字,打印出所有的排列,如512234,412325等。
要求:“4”不能在第三位,3与5不能相连。
思路:
1、把问题看成图的遍历问题,6个数字就是6个节点,所有节点的遍历就是6个数字的排列。
2、3与5不能相连,即要求3与5之间不能连通。
3、所有的排列不能有重复的情况,因为六个数字中有两个2,所有肯定会有重复,这里考虑将结果放到Set中去掉重复排列。
4、4不能放在第三位,需要在结果集中去掉不满足题目要求的遍历结果。
import java.util.Iterator;
import java.util.Set;
import java.util.TreeSet;
/**
* @author LilyLee
* @date 2017年4月26日
* @time 上午9:40:11
* @Version 1.0
* @email lilylee_1213@foxmail.com
*
*/
public class DigitalArrangement {
private String[] b=new String[]{"1","2","2","3","4","5"};
private int len=b.length;
private boolean[] visited=new boolean[len];
private int [][] a=new int[len][len];
private String result="";