原題鏈接在這里:https://leetcode.com/problems/permutations/
題目:
Given a collection of?distinct?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]
.
題解:
與Combinations相似,都是NP問題可以采用遞歸加回朔,遞歸的終止條件與Combinations相同,item.size()滿足要求就把item加到res里。
這里采用boolean [] used數組來代表當前數是否被用過。若是被用過就跳過,沒有被用過把nums[i]加到item中,然后遞歸剩下的元素。
當遞歸結束后,減掉item尾部元素,同時需要維護used數組,把當前位置變回false, 確保進入遞歸和結束遞歸時狀態相同。
Time Complexity: exponential.
AC Java:
1 public class Solution { 2 public List<List<Integer>> permute(int[] nums) { 3 List<List<Integer>> res = new ArrayList<List<Integer>>(); 4 if(nums == null || nums.length == 0){ 5 return res; 6 } 7 boolean [] used = new boolean[nums.length]; 8 helper(nums,used,new ArrayList<Integer>(), res); 9 return res; 10 } 11 private void helper(int[] nums, boolean [] used, List<Integer> item, List<List<Integer>> res){ 12 if(item.size() == nums.length){ 13 res.add(new ArrayList<Integer>(item)); 14 return; 15 } 16 for(int i = 0; i<nums.length; i++){ 17 if(!used[i]){ 18 used[i] = true; 19 item.add(nums[i]); 20 helper(nums,used,item,res); 21 item.remove(item.size()-1); 22 used[i] = false; 23 } 24 } 25 } 26 }
這道題的迭代方法如下:
與Subsets相似,開始時item先加nums[0], 把item加到res里.
然后每次添加新的nums[i], 首先把res里的每一個item拿出來, 用cur表示.
在cur的所有可能位置加上新的元素nums[i], 然后把它加載回res里。
Note: res原有的item不能保留,所以每次掃描res所有item前新建newRes, 添加完新元素nums[i]的item是要加到newRes中去的,所有可能的item都加完后再把newRes賦值回res去。
Time Complexity: exponential.
AC Java:
1 public class Solution { 2 public List<List<Integer>> permute(int[] nums) { 3 List<List<Integer>> res = new ArrayList<List<Integer>>(); 4 if(nums == null || nums.length == 0){ 5 return res; 6 } 7 List<Integer> item = new ArrayList<Integer>(); 8 item.add(nums[0]); 9 res.add(item); 10 11 for(int i = 1; i<nums.length; i++){ 12 List<List<Integer>> newRes = new ArrayList<List<Integer>>(); 13 for(int j = 0; j<res.size(); j++){ 14 List<Integer> cur = res.get(j); 15 for(int k = 0; k<=cur.size(); k++){ 16 // 記得這里要做個copy, 不能直接在原來的cur上加 17 item = new ArrayList<Integer>(cur); 18 item.add(k, nums[i]); 19 newRes.add(item); 20 } 21 } 22 res = newRes; 23 } 24 return res; 25 } 26 }
跟上Permutations II.