一道算法题目,值得一看

算法程序题:

该公司笔试题就1个,要求在10分钟内作完。

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


下面的代码是网上的一位老兄写的,值得参考一下:

上面的程序还可以改进一下的,各位有时间可以想一想.


 

  1. import java.util.Iterator;   
  2. import java.util.TreeSet;   
  3.   
  4. public class TestQuestion {   
  5.   
  6. private String[] b = new String[]{"1""2""2""3""4""5"};   
  7. private int n = b.length;   
  8. private boolean[] visited = new boolean[n];   
  9. private int[][] a = new int[n][n];   
  10. private String result = "";   
  11. private TreeSet set = new TreeSet();   
  12.   
  13. public static void main(String[] args) {   
  14. new TestQuestion().start();   
  15. }   
  16.   
  17. private void start() {   
  18.   
  19. // Initial the map a[][]   
  20. for (int i = 0; i < n; i++) {   
  21. for (int j = 0; j < n; j++) {   
  22. if (i == j) {   
  23. a[i][j] = 0;   
  24. else {   
  25. a[i][j] = 1;   
  26. }   
  27. }   
  28. }   
  29.   
  30. // 3 and 5 can not be the neighbor.   
  31. a[3][5] = 0;   
  32. a[5][3] = 0;   
  33.   
  34. // Begin to depth search.   
  35. for (int i = 0; i < n; i++) {   
  36. this.depthFirstSearch(i);   
  37. }   
  38.   
  39. // Print result treeset.   
  40. Iterator it = set.iterator();   
  41. while (it.hasNext()) {   
  42. String string = (String) it.next();   
  43. // "4" can not be the third position.   
  44. if (string.indexOf("4") != 2) {   
  45. System.out.println(string);   
  46. }   
  47. }   
  48. }   
  49.   
  50. private void depthFirstSearch(int startIndex) {   
  51. visited[startIndex] = true;   
  52. result = result + b[startIndex];   
  53. if (result.length() == n) {   
  54. // Filt the duplicate value.   
  55. set.add(result);   
  56. }   
  57. for(int j = 0; j < n; j++) {   
  58. if (a[startIndex][j] == 1 && visited[j] == false) {   
  59. depthFirstSearch(j);   
  60. else {   
  61. continue;   
  62. }   
  63. }   
  64.   
  65. // restore the result value and visited value after listing a node.   
  66. result = result.substring(0, result.length() -1);   
  67. visited[startIndex] = false;   
  68. }   
  69. }   
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值