回溯算法解决所有子集排列问题
形式一:元素无重复,且不可复选,即nums中所有元素均唯一,且最多使用一次
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
|
void backtrack(int[] nums, int start) { for (int i = start; i < nums.length; i++) { track.addLast(nums[i]); backtrack(nums, i + 1); track.removeLast(); } }
void backtrack(int[] nums) { for (int i = 0; i < nums.length; i++) { if (used[i]) { continue; } used[i] = true; track.addLast(nums[i]);
backtrack(nums); track.removeLast(); used[i] = false; } }
|
形式二:元素有重复,但是不可以复选,即nums中存在重复的元素,但是每个元素只能使用一次
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
| Arrays.sort(nums);
void backtrack(int[] nums, int start) { for (int i = start; i < nums.length; i++) { if (i > start && nums[i] == nums[i - 1]) { continue; } track.addLast(nums[i]); backtrack(nums, i + 1); track.removeLast(); } }
Arrays.sort(nums);
void backtrack(int[] nums) { for (int i = 0; i < nums.length; i++) { if (used[i]) { continue; } if (i > 0 && nums[i] == nums[i - 1] && !used[i - 1]) { continue; } used[i] = true; track.addLast(nums[i]);
backtrack(nums); track.removeLast(); used[i] = false; } }
|
形式三:元素无重复,但是可以复选
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| void backtrack(int[] nums, int start) { for (int i = start; i < nums.length; i++) { track.addLast(nums[i]); backtrack(nums, i); track.removeLast(); } }
void backtrack(int[] nums) { for (int i = 0; i < nums.length; i++) { track.addLast(nums[i]); backtrack(nums); track.removeLast(); } }
|