java字串全排列問題(經典)

來源:互聯網
上載者:User

*原題如下:用1、2、2、3、4、6這六個數字,用java寫一個main函數,列印出所有不同的排列,
*如:612234、412346等,要求:"4"不能在第三位,"3"與"6"不能相連.
*
*1把問題歸結為圖結構的遍曆問題。實際上6個數字就是六個結點,把六個結點串連成無向連通圖,對於每一個結點求這個圖形的遍曆路徑,
*所有結點的遍曆路徑就是最後對這6個數位排列組合結果集。
*2顯然這個結果集還未達到題目的要求。從以下幾個方面考慮:
*1.3,6不能相連:實際要求這個連通圖的結點3,5之間不能連通,可在構造圖結構時就滿足改條件,然後再遍曆圖。
*2.不能有重複:考慮到有兩個2,明顯會存在重複結果,可以把結果集放在TreeSet中過濾重複結果
*3.4不能在第三位:仍舊在結果集中去除滿足此條件的結果。

import java.util.Iterator;
import java.util.TreeSet;

public class Sort {

     private String[] b = new String[] {"1","2","2","3","4","6"};

     private int n = b.length;

     private boolean[] visited = new boolean[n];

     private int[][] a = new int[n][n];

     private String result = "";

     private TreeSet<String> set = new TreeSet<String>();

     public static void main(String[] args) {
         new Sort().start();
     }

     private void start() {

         // Initial the map a[][]
         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 and 5 can not be the neighbor.
         a[3][5] = 0;
         a[5][3] = 0;

         // Begin to depth search.
         for (int i = 0; i < n; i++) {
             this.depthFirstSearch(i);
         }

         // Print result treeset.
         Iterator it = set.iterator();
         while (it.hasNext()) {
             String string = (String) it.next();
             System.out.println(string);
         }
     }

     private void depthFirstSearch(int startIndex) {
         visited[startIndex] = true;
         result = result + b[startIndex];
         if (result.length() == n) {
             // "4" can not be the third position.
             if (result.indexOf(" 4 ") != 2) {
                 // Filt the duplicate value.
                 set.add(result);
             }
         }
         for (int j = 0; j < n; j++) {
             if (a[startIndex][j] == 1 && visited[j] == false) {
                 depthFirstSearch(j);
             }
         }

         // restore the result value and visited value after listing a node.
         result = result.substring(0, result.length() - 1);
         visited[startIndex] = false;
     }
}
 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.