2023-04-24 03:33:30 +08:00
|
|
|
/**
|
|
|
|
* File: permutations_ii.java
|
|
|
|
* Created Time: 2023-04-24
|
|
|
|
* Author: Krahets (krahets@163.com)
|
|
|
|
*/
|
|
|
|
|
|
|
|
package chapter_backtracking;
|
|
|
|
|
|
|
|
import java.util.*;
|
|
|
|
|
|
|
|
public class permutations_ii {
|
|
|
|
/* 回溯算法:全排列 II */
|
2023-04-27 01:18:18 +08:00
|
|
|
static void backtrack(List<Integer> state, int[] choices, boolean[] selected, List<List<Integer>> res) {
|
2023-04-24 03:33:30 +08:00
|
|
|
// 当状态长度等于元素数量时,记录解
|
|
|
|
if (state.size() == choices.length) {
|
|
|
|
res.add(new ArrayList<Integer>(state));
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
// 遍历所有选择
|
|
|
|
Set<Integer> duplicated = new HashSet<Integer>();
|
|
|
|
for (int i = 0; i < choices.length; i++) {
|
|
|
|
int choice = choices[i];
|
|
|
|
// 剪枝:不允许重复选择元素 且 不允许重复选择相等元素
|
|
|
|
if (!selected[i] && !duplicated.contains(choice)) {
|
2023-04-27 01:18:18 +08:00
|
|
|
// 尝试:做出选择,更新状态
|
2023-04-24 03:33:30 +08:00
|
|
|
duplicated.add(choice); // 记录选择过的元素值
|
2023-04-27 01:18:18 +08:00
|
|
|
selected[i] = true;
|
|
|
|
state.add(choice);
|
2023-04-24 03:33:30 +08:00
|
|
|
backtrack(state, choices, selected, res);
|
2023-04-27 01:18:18 +08:00
|
|
|
// 回退:撤销选择,恢复到之前的状态
|
|
|
|
selected[i] = false;
|
|
|
|
state.remove(state.size() - 1);
|
2023-04-24 03:33:30 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-04-27 01:18:18 +08:00
|
|
|
/* 全排列 II */
|
|
|
|
static List<List<Integer>> permutationsII(int[] nums) {
|
|
|
|
List<List<Integer>> res = new ArrayList<List<Integer>>();
|
|
|
|
backtrack(new ArrayList<Integer>(), nums, new boolean[nums.length], res);
|
|
|
|
return res;
|
|
|
|
}
|
|
|
|
|
2023-04-24 03:33:30 +08:00
|
|
|
public static void main(String[] args) {
|
|
|
|
int[] nums = { 1, 2, 2 };
|
|
|
|
|
2023-04-27 01:18:18 +08:00
|
|
|
List<List<Integer>> res = permutationsII(nums);
|
2023-04-24 03:33:30 +08:00
|
|
|
|
|
|
|
System.out.println("输入数组 nums = " + Arrays.toString(nums));
|
|
|
|
System.out.println("所有排列 res = " + res);
|
|
|
|
}
|
|
|
|
}
|