[LeetCode][Java] Permutations

來源:互聯網
上載者:User

標籤:leetcode   java   permutations   

題目:

Given 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].

題意:

給定一組數字,返回所有的可能的組合。

比如:

[1,2,3]有下面的組合:

[1,2,3][1,3,2][2,1,3][2,3,1][3,1,2], and [3,2,1].

演算法分析:

建立樹,並進行遞迴 參考部落格:http://blog.csdn.net/tuantuanls/article/details/8717262 思路二

建立一棵樹,比如說:


對於第k層節點來說,就是交換固定了前面 k-1 位,然後分別 swap(k,k), swap(k, k+1) , swap(k, k+2) ...
例如中的第三層,固定了第一位(即2),然後分別交換第1,1位,1,2位,1,3位

AC代碼:

public class Solution {    public ArrayList<ArrayList<Integer>> permute(int[] num)     {    ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();    permute(num, 0, result);    return result;    }    void permute(int[] num, int start, ArrayList<ArrayList<Integer>> result)     {    if (start >= num.length) //終止條件,遞迴到末尾節點是,將數組轉化為鏈表    {    ArrayList<Integer> item = convertArrayToList(num);    result.add(item);    }    for (int j = start; j <= num.length - 1; j++)    {    swap(num, start, j);//交換    permute(num, start + 1, result);//交換後子代遞迴    swap(num, start, j);//恢複到交換前的初始狀態,以便於得出下一次的交換結果    }    }    private ArrayList<Integer> convertArrayToList(int[] num) //數組變鏈表    {    ArrayList<Integer> item = new ArrayList<Integer>();    for (int h = 0; h < num.length; h++)     item.add(num[h]);    return item;    }    private void swap(int[] a, int i, int j) //交換    {    int temp = a[i];    a[i] = a[j];    a[j] = temp;    }}


著作權聲明:本文為博主原創文章,轉載註明出處

[LeetCode][Java] Permutations

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.