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].
思路: 典型的backtracking,注意list在递归的过程一直在变化,所以每次加入的list需要重新创建。result.add(new ArrayList<Integer>(list));
时间复杂度:O(n!)
空间复杂度:O(n)
public class Solution {
public List<List<Integer>> permute(int[] nums) {
List<List<Integer>> result = new ArrayList<List<Integer>>();
List<Integer> list = new ArrayList<Integer>();
helper(result, list, nums);
return result;
}
private void helper(List<List<Integer>> result, List<Integer> list, int[] nums) {
if (list.size() == nums.length) {
if (!result.contains(list)) {
result.add(new ArrayList<Integer>(list));
return;
}
}
for (int i = 0; i < nums.length; i++) {
if (list.contains(nums[i])) {
continue;
}
list.add(nums[i]);
helper(result,list,nums);
list.remove(list.size() - 1);
}
}
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。