问题描述:针对1、2、2、3、4、5这6个数字,写一个函数,打印出所有不同的排列,例如512234,215432等,要求“4”不能再第三位,“3”,“5”不能相连。
思路:针对这个问题,可以将6个节点构成一个无向连通图。由于3和5不能相连,因此在构造图时3和5不能相连。对于4不能出现在第三位可以在遍历结束时判断。
代码如下:
import java.util.LinkedList; import java.util.Set; import java.util.TreeSet; public class QuanPailie { private int[] numbers = new int[] { 1, 2, 2, 3, 4, 5 }; private int n = numbers.length; private boolean[] visited = new boolean[n]; private int[][] gra = new int[n][n]; private Set<String> set = new TreeSet<String>(); private LinkedList<Integer> stack = new LinkedList<Integer>(); public Set<String> getAll() { buildGra(); for (int i = 0; i < n; i++) { dfs(i, stack); } return set; } private void buildGra() { for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (i == j) { gra[i][j] = 0; } else { gra[i][j] = 1; } } } gra[5][3] = 0; gra[3][5] = 0; } private void dfs(int i, LinkedList<Integer> stack) { visited[i]=true; stack.addLast(numbers[i]); if (stack.size() == 6 && stack.get(2) != 4) { set.add(fromStackToString(stack)); } for(int j = 0; j <n; j++) { if(gra[i][j]!=0&&visited[j]==false) dfs(j, stack); } stack.removeLast(); visited[i]=false; } private String fromStackToString(LinkedList<Integer> linkedList) { StringBuilder builder = new StringBuilder(); for (Integer integer : linkedList) { builder.append(integer); } return builder.toString(); } public static void main(String[] args) { QuanPailie pailie=new QuanPailie(); Set<String> set=pailie.getAll(); for (String string : set) { System.out.println(string); } } }