题意以及限制条件
-
题目:
-
限制条件:
想到的所有可能解法
-
Ways_1——回溯
- 时间复杂度——O(n*logn);空间复杂度——O(n);
- 求解集合{1,1,1,2}的全排列的回溯过程如下:
对应的代码
- Ways_1
class Solution {
public List<List<Integer>> permuteUnique(int[] nums) {
List<List<Integer>> list = new ArrayList<List<Integer>>();
Arrays.sort(nums);
backtrack(list, new ArrayList<Integer>(), nums, new boolean[nums.length]);
return list;
}
private static void backtrack(List<List<Integer>> list, List<Integer> templist, int[] nums, boolean[] used) {
if (templist.size() == nums.length) {
list.add(new ArrayList<Integer>(templist));
} else {
for (int i = 0; i < nums.length; ++i) {
if (used[i] || i > 0 && nums[i] == nums[i - 1] && !used[i - 1]) {
continue;
}
used[i] = true;
templist.add(nums[i]);
backtrack(list, templist, nums, used);
used[i] = false;
templist.remove(templist.size() - 1);
}
}
}
}