47. 全排列 II(去重版)

要求不要出现重复的排列
a a c
思路:有重复字符的话
在做选择时要去掉相同的字符选择
第一个字符有两种选择(a,c)
第二个字符也有两种选择(a,c)
第三个字符只有一种选择
public static List<String> getAllC(String s){
//准备收集的结果集
List<String> ans =new ArrayList<>();
//把待处理字符串处理成字符集合
List<Character> chs=new ArrayList<>();
for(char cha:s.toCharArray()){
chs.add(cha);
}
//递归处理
process(chs,"",ans);
return ans;
}
/**
*
chs中的所有字符都可以选择,
形成的所有全排列放入到ans中
沿途的决定是path
*/
public static void process(List<Character> chs,String path,List<String> ans){
//base case
if(chs.isEmpty()){
ans.add(path);
return;
}
HashSet<Character> pickSet=new HashSet<>();
//chs中每个字符都可以作为当前字符,但是一旦当前决定要,后续就不能再使用了
for(int i=0;i<chs.size();i++){
//分别将i作为当前的决定,
if(!pickSet.contains(chs.get(i))){
pickSet.add(chs.get(i));
//这里要特别注意,不能用path+=,而要重新申请一个变量来接
String pick=path+chs.get(i);
//拷贝一分,再把当前位置的字符去掉,相当于把当前字符排除了考虑
List<Character> next=new ArrayList<>(chs);
//把当前位置的字符移除掉
next.remove(i);
process(next,pick,ans);
}
}
}
47. 全排列 II
给定一个可包含重复数字的序列 nums ,按任意顺序 返回所有不重复的全排列。
示例 1:
输入:nums = [1,1,2]
输出:
[[1,1,2],
[1,2,1],
[2,1,1]]
class Solution {
public List<List<Integer>> permuteUnique(int[] nums) {
List<List<Integer>> ans=new ArrayList<>();
List<Integer> numList=new ArrayList<>();
for(int i=0;i<nums.length;i++){
numList.add(nums[i]);
}
List<Integer> path=new ArrayList<>();
process(numList,path,ans);
return ans;
}
private void process(List<Integer> numList,List<Integer> path,List<List<Integer>> ans){
//base case
if(numList.isEmpty()){
ans.add(path);
return;
}
HashSet<Integer> set=new HashSet<>();
for(int i=0;i<numList.size();i++){
if(!set.contains(numList.get(i))){
set.add(numList.get(i));
List<Integer> pickList=new ArrayList<>(path);
pickList.add(numList.get(i));
List<Integer> nextList=new ArrayList<>(numList);
nextList.remove(i);
process(nextList,pickList,ans);
}
}
}
}

浙公网安备 33010602011771号