46. 全排列

注意我们这次每次都重复去取元素,所以不需要starIndex,但是需要记录每个元素是否被用过,所以加入一个boolean[] used
class Solution {List<List<Integer>> result = new ArrayList<>();List<Integer> path = new ArrayList<>();private void backTracking(int[] nums,boolean[] used){if (path.size() == nums.length){result.add(new ArrayList<>(path));return;}for (int i = 0; i < nums.length; i++) {if (used[i] == true){//true说明已经被用过,跳过continue;}used[i] = true;//因为用了,标志truepath.add(nums[i]);backTracking(nums,used);used[i] = false;//回溯,重新标志falsepath.remove(path.size()-1);}}public List<List<Integer>> permute(int[] nums) {boolean[] used = new boolean[nums.length];backTracking(nums,used);return result;}}
// 解法2:通过判断path中是否存在数字,排除已经选择的数字class Solution {List<List<Integer>> result = new ArrayList<>();LinkedList<Integer> path = new LinkedList<>();public List<List<Integer>> permute(int[] nums) {if (nums.length == 0) return result;backtrack(nums, path);return result;}public void backtrack(int[] nums, LinkedList<Integer> path) {if (path.size() == nums.length) {result.add(new ArrayList<>(path));}for (int i =0; i < nums.length; i++) {// 如果path中已有,则跳过if (path.contains(nums[i])) {continue;}path.add(nums[i]);backtrack(nums, path);path.removeLast();}}}
47. 全排列 II

class Solution {List<List<Integer>> result = new ArrayList<>();List<Integer> path = new ArrayList<>();private void backTracking(int[] nums, boolean[] used) {if (nums.length == path.size()) {result.add(new ArrayList<>(path));return;}for (int i = 0; i < nums.length; i++) {if (i > 0 && nums[i] == nums[i - 1] && used[i - 1] == false) continue;if (used[i] == false) {used[i] = true;path.add(nums[i]);backTracking(nums, used);path.remove(path.size() - 1);used[i] = false;}}}public List<List<Integer>> permuteUnique(int[] nums) {Arrays.sort(nums);boolean[] used = new boolean[nums.length];backTracking(nums, used);return result;}}
