题目
跟另外一个题目很像:字符串的排列
法1:DFS,最佳解法
class Solution {
public List<List<Integer>> permute(int[] nums) {
List<List<Integer>> res = new ArrayList<>();
if (nums.length == 0) {
return res;
}
dfs(nums, 0, res);
return res;
}
public void dfs(int[] nums, int curInx, List<List<Integer>> res) {
if (curInx == nums.length - 1) {
List<Integer> tmp = new ArrayList<>();
for (int i = 0; i < nums.length; ++i) {
tmp.add(nums[i]);
}
res.add(tmp);
return;
}
for (int i = curInx; i < nums.length; ++i) {
swap(nums, curInx, i);
dfs(nums, curInx + 1, res);
swap(nums, curInx, i);
}
}
public void swap(int[] array, int i, int j) {
int tmp = array[i];
array[i] = array[j];
array[j] = tmp;
}
}