标签:
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]
.
Traditional backtracking way to solve this problem.
1 public class Solution { 2 public List<List<Integer>> permute(int[] nums) { 3 Arrays.sort(nums); 4 int length = nums.length; 5 List<List<Integer>> result = new ArrayList<List<Integer>>(); 6 boolean[] visited = new boolean[length]; 7 8 dfs(nums, visited, new ArrayList<Integer>(), result); 9 return result; 10 } 11 12 private void dfs(int[] nums, boolean[] visited, List<Integer> record, List<List<Integer>> result) { 13 if (record.size() == nums.length) { 14 if (!result.contains(record)) 15 result.add(new ArrayList<Integer>(record)); 16 return; 17 } 18 for (int i = 0; i < nums.length; i++) { 19 if (!visited[i]) { 20 record.add(nums[i]); 21 visited[i] = true; 22 dfs(nums, visited, record, result); 23 // Restore 24 record.remove(record.size() - 1); 25 visited[i] = false; 26 } 27 } 28 } 29 }
标签:
原文地址:http://www.cnblogs.com/ireneyanglan/p/4884556.html