打印到类阵列的给定序列的所有排列的n皇后问题
2015-09-22 11:47
573 查看
题目例如以下:Given
a collection of numbers, return all possible permutations.
For example,
and
分析:假设仅仅是求排列数非常好算,可是要打印全部排列且不反复比較困难。
假设单纯用for循环或递归。非常easy出现死循环。
而假设用随机生成排列,直到打印出全部排列。又easy超时。
因此通过对问题的分析,发现能够将原问题映射成为n皇后问题。每一次排列映射为n皇后的一次成功摆放,打印全部的排列即打印全部摆放皇后的方法。但与n皇后问题不同的是。此问题皇后不能放在同行同列,却能够放在对角线。因此核心还是回溯法,代码例如以下:
a collection of numbers, return all possible permutations.
For example,
[1,2,3]have the following permutations:
[1,2,3],
[1,3,2],
[2,1,3],
[2,3,1],
[3,1,2],
and
[3,2,1].
分析:假设仅仅是求排列数非常好算,可是要打印全部排列且不反复比較困难。
假设单纯用for循环或递归。非常easy出现死循环。
而假设用随机生成排列,直到打印出全部排列。又easy超时。
因此通过对问题的分析,发现能够将原问题映射成为n皇后问题。每一次排列映射为n皇后的一次成功摆放,打印全部的排列即打印全部摆放皇后的方法。但与n皇后问题不同的是。此问题皇后不能放在同行同列,却能够放在对角线。因此核心还是回溯法,代码例如以下:
import java.util.ArrayList; import java.util.Stack; public class Main { public static void main(String[] args) { int[] num={1}; ArrayList<ArrayList<Integer>> result=new ArrayList<ArrayList<Integer>>(); result=permute(num); System.out.print(result); } public static ArrayList<ArrayList<Integer>> permute(int[] num) { ArrayList<ArrayList<Integer>> result=new ArrayList<ArrayList<Integer>>(); ArrayList<Integer> elem=new ArrayList<Integer>(); int QueueNum=num.length; Stack<Integer> QueuePos=new Stack<Integer>(); if(num.length==0) return result; if(num.length==1) { elem.add(num[0]); result.add(elem); return result; } int row; QueuePos.push(0); row=0; while(row>=0) { put_queue(QueuePos,row,QueueNum); //皇后放置完成 for(int i=0;i<QueuePos.size();i++) { elem.add(num[QueuePos.get(i)]); } result.add(elem); elem=new ArrayList<Integer>(); //寻找下一个方法 row=find_next(QueuePos,QueueNum); //status=put_queue(QueuePos,row,QueueNum); } return result; } public static int find_next(Stack<Integer> QueuePos,int QueueNum) { int row,column; row=QueueNum-2; QueuePos.pop(); column=QueuePos.pop(); column=column+1; while(row>=0) { if(column<QueueNum&&!QueuePos.contains(column)) { QueuePos.push(column); return row; } else if(column==QueueNum) { row--; if(row<0) return row; column=QueuePos.pop(); column=column+1; }else { column++; } } return row; } public static boolean put_queue(Stack<Integer> QueuePos,int row,int QueueNum) { int i,j,column; //i代表行。j代表列 i=row+1; while(i<QueueNum) { for(j=0;j<QueueNum;j++) if(!QueuePos.contains(j)) break; if(j!=QueueNum) { QueuePos.push(j); i++; j=0; } else { i--; if(i>=0) { column=QueuePos.pop(); QueuePos.push(column+1); }else return false; } } return true; } }
相关文章推荐
- 2015 Objective-C 三大新特性
- 查阅参考资料的技巧
- C#/Net代码精简优化技巧(3)
- Spring MVC POST中文乱码解决方案
- Django搭建简单网页的学习笔记 之三(View)
- 【设计模式】——依赖倒转原则
- Android 搜索 把软键盘上的回车键改为搜索
- from声明
- javascript三级联动效果实现2
- 如何使用HibernateTemplate进行分页功能
- Maven搭建SpringMVC+Mybatis项目详解
- libevent之event_base
- ORACLE随机数DBMS_RANDOM包
- [Leetcode]Binary Tree Inorder Traversal
- 同一Activity实例被多次重复创建的解决方法
- C++ 引用
- JSP入门教程之客户端验证、常用输出方式及JSTL基本用法
- 物理引擎中velocity的单位是个什么鬼?
- 物理引擎中velocity的单位是个什么鬼?
- 生活中的MVC模式,一个吃货的理解