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]
.
同样是backtracking,与combinations极其类似,不过该题中需要用到一个visited数组来标记一下某个元素是否访问过。
public List<List<Integer>> permute(int[] nums) { List<List<Integer>> list = new ArrayList<List<Integer>>(); List<Integer> item = new ArrayList<Integer>(); if (nums==null || nums.length==0) { return list; } boolean[] visited = new boolean[nums.length]; dfsHelper(list, item, nums, visited); return list; } public void dfsHelper(List<List<Integer>> list, List<Integer> item, int[] nums, boolean[] visited){ if (item.size()==nums.length) { list.add(new ArrayList<Integer>(item)); return ; } for (int i = 0; i < nums.length; i++) { if (!visited[i]) { item.add(nums[i]); visited[i] = true; dfsHelper(list, item, nums, visited); visited[i] = false; item.remove(item.size()-1); } } }