题目描述:
标签: 回溯算法
给定一个 没有重复 数字的序列,返回其所有可能的全排列。
代码:
思路分析:
其实 求排列 和 求组合 的思路特别类似,但要注意的就是:(组合的相关思路可以见以前的题目)
1、定义一个used[nums.length]的数组记录元素各个位置上的元素是否使用过,如果使用过,就continue跳过本次循环
2、不需要startIndex
3、注意【1,2】和【2,1】是两种不同的排列
class Solution {
List<List<Integer>> result = new ArrayList<>();
List<Integer> path = new ArrayList<>();
public List<List<Integer>> permute(int[] nums) {
boolean[] used = new boolean[nums.length];
backTracing(nums,used);
return result;
}
public void backTracing(int[] nums,boolean[] used){
if(path.size() == nums.length){
result.add(new ArrayList<Integer>(path));
return;
}
for(int i = 0;i < nums.length;i++){
if(used[i] == true){
continue;
}
path.add(nums[i]);
used[i] = true;
backTracing(nums,used);
used[i] = false;
path.remove(path.size() - 1);
}
}
}