【Java/算法/排列】列举出由1,2,3,4,5,6组成的,没有重复数字,且1,3都不与5相邻的六位偶数?
【题干】
由1,2,3,4,5,6组成的,没有重复数字,且1,3都不与5相邻的六位偶数的个数是?(此题为10年四川高考理科第10题)
【数学解答】
末位是246选1,其余全排列,总数是C31A55=360种;(C31表示三中选一,A55表示5个全排列)
相邻即捆绑,捆绑比不相邻更容易考虑;
假设末位为6,1,5捆绑后与2,3,4全排,1,5内部有两种排列方式,有C31A44A22种;
同理3,5捆绑有C31A44A22种;
假设末位为6,把5放13中间与2,4去安排,135内部有531,135两种形式,有C31A33A22种;
Sum=C31A55-2*C31A44A22+C31A33A22=108种;
【程序解答】
总数计有360种,全排为720种,用条件筛选掉奇数和15,35相邻的就行;
代码:
import java.util.ArrayList; import java.util.List; public class Arrange3 { static List<List<Integer>> results = new ArrayList<>(); public static void main(String[] args) { int[] arr = {1,2,3,4,5,6}; Arrange3 h1 = new Arrange3(); h1.dfs(arr,new ArrayList<>()); int idx=0; for (List<Integer> currLs : results) { // 1.奇偶间隔校验 int first=currLs.get(0); int second=currLs.get(1); int third=currLs.get(2); int forth=currLs.get(3); int fifth=currLs.get(4); int sixth=currLs.get(5); // 1.偶数校验 if(sixth%2!=0) { continue; } // 2.1,3都不与5相邻捆绑校验 if(first==5) { if(second==1 || second==3) { continue; } } if(sixth==5) { if(fifth==1 || fifth==3) { continue; } } boolean flag=false; for(int i=1;i<6;i++) { if(currLs.get(i)==5) { if(currLs.get(i-1)==1 || currLs.get(i+1)==3 || currLs.get(i-1)==3 || currLs.get(i+1)==1) { flag=true; break; } } } if(flag) { continue; } System.out.println(String.format("%02d",++idx)+"."+currLs); } } public List<List<Integer>> dfs( int[] arr,List<Integer> list){ List<Integer> temp = new ArrayList<>(list); if (arr.length == list.size()){ results.add(temp); } for (int i=0;i<arr.length;i++){ if (temp.contains(arr[i])){ continue; } temp.add(arr[i]); dfs(arr,temp); temp.remove(temp.size()-1); } return results; } }
【输出】
01.[1, 2, 3, 4, 5,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, 4, 1, 3, 2] 100.[5, 6, 4, 3, 1, 2] 101.[6, 1, 3, 2, 5, 4] 102.[6, 1, 3, 4, 5, 2] 103.[6, 3, 1, 2, 5, 4] 104.[6, 3, 1, 4, 5, 2] 105.[6, 5, 2, 1, 3, 4] 106.[6, 5, 2, 3, 1, 4] 107.[6, 5, 4, 1, 3, 2] 108.[6, 5, 4, 3, 1, 2]
【参考资料】
1.《新编中学数学解题方法1000招丛书【排列和组合】》P99 刘培杰工作室编 哈尔滨工业大学出版社出版
2.https://www.jb51.net/article/252294.htm
END