用1、2、2、3、4、5这六个数字,用java写一个main函数,打印出所有不同的排列,如:512234、412345等,要求:"4"不能在第三位,"3"与"5"不能相连。

时间:2023-03-08 17:05:53

最近在看算法,看到这个题,觉得挺经典的,收起。

分析:

1 、把问题归结为图结构的遍历问题。实际上6个数字就是六个结点,把六个结点连接成无向连通图,对于每一个结点求这个图形的遍历路径,所有结点的遍历路径就是最后对这  6个数字的排列组合结果集。
        2、 3,5不能相连:实际要求这个连通图的结点3,5之间不能连通, 可在构造图结构时就满足改条件,然后再遍历图。
        3、 不能有重复: 考虑到有两个2,明显会存在重复结果,可以把结果集放在TreeSet中过滤重复结果
        4、   4不能在第三位: 仍旧在结果集中去除满足此条件的结果。

package JingDian;

import java.util.Iterator;
import java.util.TreeSet; public class numberRandom {
String[] stra = {"1","2","2","3","4","5"};
int n = stra.length;
boolean[] visited = new boolean[n];
String result = "";
TreeSet<String> ts = new TreeSet<String>();
int[][] a = new int[n][n];
private void searchMap()
{ for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
if(i==j)
{
//图中对角线部分是无法访问的
a[i][j]=0;
}else{
a[i][j]=1;
}
}
}
//3和5不能相连
a[3][5]=0;
a[5][3]=0;
//开始遍历
for(int i=0;i<n;i++)
{
search(i);
}
Iterator<String> it = ts.iterator();
while(it.hasNext())
{
String str =it.next();
//4不能在第三位
if(str.indexOf("4")!=2){
System.out.println(str);
}
}
}
//这是个深度优先的遍历
private void search(int startIndex){
visited[startIndex] = true;
result = result + stra[startIndex];
if(result.length() ==n)
{
ts.add(result);
}
for(int j=0;j<n;j++)
{
if(a[startIndex][j]==1&&visited[j]==false)
{
search(j);
}else
{
continue;
}
}
//一个result结束后踢掉最后一个,寻找别的可能性,若没有的话,则继续向前踢掉当前最后一个
result = result.substring(0,result.length()-1);
visited[startIndex] = false; } public static void main(String[] args){
new numberRandom().searchMap(); } }