Given a collection of numbers that might contain duplicates, return all possible unique permutations.
For example,
[1,1,2] have the following unique permutations:
[1,1,2], [1,2,1], and [2,1,1].
這道題跟上一道題(Permutations)差不多,但竟然是hard等級。
上一道題做出來後只要稍微修改一下,在遞歸前,如果提取出來的元素跟上一次提取出來的元素一樣就continue。
否則就跟上一道題是一樣的。
如何初始化存儲上一個元素的tmp值呢。
我一開始用-1,結果測試集中含有-1直接報錯,然後我就用了tmp=num.get(0)-1;因爲num是經過排序的,所以這樣子tmp就不會和任何一個num中有重複了。但是如果考慮到num中恰好包含Integer.minValue的話···
上代碼
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Permutations_II {
/**
Given a collection of numbers that might contain duplicates, return all possible unique permutations.
For example,
[1,1,2] have the following unique permutations:
[1,1,2], [1,2,1], and [2,1,1].
* @param args
*/
public List<List<Integer>> getpermute(List<Integer> num) {
List<List<Integer>> resultLists=new ArrayList<>();
if(num.size()==1){
resultLists.add(num);
}
else{
int first=-1;
for(int indexnum=0;indexnum<num.size();++indexnum){
List<Integer> numtmp=new ArrayList<>(num);
if(first==numtmp.get(indexnum))continue;
first=numtmp.remove(indexnum);
List<List<Integer>> tmplLists=getpermute(numtmp);
for (List<Integer> list : tmplLists) {
list.add(0, first);
resultLists.add(list);
}
}
}
return resultLists;
}
public List<List<Integer>> permuteUnique(int[] num) {
Arrays.sort(num);
List<Integer> numlist=new ArrayList<>();
for(int indexnum=0;indexnum<num.length;++indexnum)numlist.add(num[indexnum]);
return getpermute(numlist);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
}
}