標籤: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