1. 程式人生 > >把一個數組裡的數組合全部列出(遞迴)

把一個數組裡的數組合全部列出(遞迴)

把一個數組裡的數組合全部列出,比如1和2列出來為12,21

code

思路就是固定字首 prefix,然後還有剩下的候選candidate。從候選裡面選擇一些加到字首後面。
比如固定字首1,然後加上2,再從後面的34 選中3,然後是4。得到1234。或者 從後面的34裡面先選4,然後是3。得到1243。

static void listAll(List candidate, String prefix) {
     if (candidate.isEmpty()) {
    System.out.println(prefix);
     }

    for (int
i = 0; i < candidate.size(); i++) { List temp = new LinkedList(candidate); listAll(temp, prefix + temp.remove(i)); } }

程式碼利用了一些特性,LinkedList 刪除操作較快,remove返回的是刪除的元素
函式的引數從右邊解析,remove 之後,temp 傳過去的值也是少了一個的容器。這樣candidate漸漸變小,才能達到遞迴跳出條件。

用 String 實現

static void listAll(String candidate, String prefix) {
    if
( candidate.length() == 0) { System.out.println(prefix); } for (int i = 0; i < candidate.length(); i++) { char prefixChar = candidate.charAt(i); listAll(candidate.replace(prefixChar + "", ""), prefix + prefixChar); } }

測試


public static void main(String[] args) throws
IOException { String[] arrays = new String[] { "1", "2", "3", "4" }; listAll(Arrays.asList(arrays), ""); listAll("1234", ""); }