给定一个没有重复数字的序列,返回其所有可能的全排列。
示例:
输入: [1,2,3]
输出:
[
[1,2,3],
[1,3,2],
[2,1,3],
[2,3,1],
[3,1,2],
[3,2,1]
]
思路:搜索回溯经典题
-
class Solution {
-
int[] visited;
//标记数组
-
List<List<Integer>> res =
new ArrayList<>();
//答案
-
public List<List<Integer>> permute(
int[] nums) {
-
visited =
new
int[nums.length];
-
backtrack(nums,
new ArrayList<Integer>());
-
return res;
-
}
-
-
private void backtrack(int[] nums, ArrayList<Integer> tmp) {
-
if (tmp.size() == nums.length) {
-
res.add(
new ArrayList<>(tmp));
-
return;
-
}
-
for (
int i =
0; i < nums.length; i++) {
-
if (visited[i] ==
1)
continue;
-
visited[i] =
1;
-
tmp.add(nums[i]);
-
backtrack(nums, tmp);
-
visited[i] =
0;
-
tmp.remove(tmp.size() -
1);
-
}
-
}
-
}
转载:https://blog.csdn.net/hebtu666/article/details/104037165
查看评论