description:
Given a list of numbers, return all possible permutations.
Notice
You can assume that there is no duplicate numbers in the list.
Have you met this question in a real interview? Yes
Example
For nums = [1,2,3], the permutations are:
[
[1,2,3],
[1,3,2],
[2,1,3],
[2,3,1],
[3,1,2],
[3,2,1]
]
解题思路:
因为题目是要求求出所有的排列的的个数,所以应该使用DFS的方式进行处理.
所有的结果都是顺序相关的,时间复杂度O(N!)
该题目没有去重的过程,所以使用的数据应该是从一开始的位置开始.
class Solution {
/**
* @param nums: A list of integers.
* @return: A list of permutations.
*/
public List<List<Integer>> permute(int[] nums) {
// write your code here
List<List<Integer>> result = new ArrayList<>();
List<Integer> list = new ArrayList<>();
if (nums == null) {
return result;
}
if (nums.length == 0) {
result.add(list);
return result;
}
util(result, list, nums);
return result;
}
private void util(List<List<Integer>> result,
List<Integer> list,
int[] nums) {
if (list.size() == nums.length) {
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]);
util(result, list, nums);
list.remove(list.size() - 1);
}
}
}