国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學(xué)院 > 開發(fā)設(shè)計 > 正文

個人記錄-LeetCode 90. Subsets II

2019-11-08 01:40:48
字體:
供稿:網(wǎng)友

問題:

Given a collection of integers that might contain duplicates, nums, return all possible subsets.

Note: The solution set must not contain duplicate subsets.

For example, If nums = [1,2,2], a solution is:

[ [2], [1], [1,2,2], [2,2], [1,2], []]

代碼示例:

解決這個,最后先回憶一下LeetCode 78。 LeetCode 78與LeetCode 90唯一的差別是,LeetCode的輸入數(shù)組中沒有重復(fù)的數(shù)據(jù)。

LeetCode 78的一種解法的思路類似于:

public class Solution { public List<List<Integer>> subsets(int[] nums) { List<List<Integer>> res = new ArrayList<>(); ArrayList<Integer> tmp = new ArrayList<>(); Arrays.sort(nums); //首先增加空集 res.add(tmp); dfs(res,tmp,nums,0); return res; } public void dfs(List<List<Integer>> res, ArrayList<Integer> tmp, int[] nums, int pos){ for(int i=pos; i<=nums.length-1;i++){ //每增加一個新的數(shù),都構(gòu)成一個新的子集 tmp.add(nums[i]); //將新的集合加入結(jié)果 res.add(new ArrayList<Integer>(tmp)); //進(jìn)入下一層的迭代 //避免重復(fù),下一個加入的數(shù),在當(dāng)前數(shù)位置的后面 dfs(res,tmp,nums,i+1); //當(dāng)前數(shù),作為本層的結(jié)尾,已經(jīng)加入了所有的結(jié)果 //需要移除,將下一個數(shù)作為本層的結(jié)果 tmp.remove(tmp.size()-1); } }}

上面代碼運(yùn)行的結(jié)果類似于:

比如,輸入集合為[1,2,3],那么依次加入的結(jié)果類似于:[] //從空集開始,每次增加一個元素,都構(gòu)成一個新的子集[1] //第1層迭代[1,2] //第2層迭代[1,2,3] //第3層迭代 //第4層迭代,pos大于length-1,無實(shí)際操作 //回到第3層,移除3 //3后面沒有其它數(shù)了,回到第2層 //移除2[1,3] //第2層跌代,加入2后面的數(shù)3 //第3層迭代,pos大于length-1,無實(shí)際操作 //回到第2層,移除3 //3后面沒有其它數(shù)了,回到第1層 //移除1[2] //第1層跌代,加入1后面的數(shù)2[2,3] //第2層跌代,加入3 //第3層迭代,pos大于length-1,無實(shí)際操作 //回到第2層,移除3 //3后面沒有其它數(shù)了,回到第1層 //移除2[3] //第1層跌代,加入2后面的數(shù)3 //第2層迭代,pos大于length-1,無實(shí)際操作 //回到第1層,移除3 //3后面沒有其它數(shù)了,結(jié)束

在LeetCode 78的基礎(chǔ)上,LeetCode 90就比較好解決了,只要避免不必要的重復(fù)就行。 代碼示例如下:

public class Solution { public List<List<Integer>> subsetsWithDup(int[] nums) { List<List<Integer>> res = new ArrayList<>(); ArrayList<Integer> tmp = new ArrayList<>(); Arrays.sort(nums); res.add(tmp); dfs(res,tmp,nums,0); return res; } public void dfs(List<List<Integer>> res, ArrayList<Integer> tmp, int[] num, int pos){ for(int i=pos;i<=num.length-1;i++){ tmp.add(num[i]); res.add(new ArrayList<>(tmp)); dfs(res,tmp,num,i+1); tmp.remove(tmp.size()-1); //就是額外增加了這一部分 while(i<num.length-1 && num[i]==num[i+1]) { i++; } } }}

舉例如下:

假設(shè)集合為[2,3,3],如果按照LeetCode 78中的代碼運(yùn)行,結(jié)果如下:[][2] //1層[2,3] //2層[2,3,3] //3層 //4層未實(shí)際運(yùn)行,回退到第3層,移除最后一個3 //3后沒其它數(shù),回到第2層 //回到第2層后,移除第2個三[2,3] //然后添加最后一個3,形成重復(fù) //以下分析類似[3][3,3][3]

因此,每層迭代,移除的數(shù)不能和新加入的數(shù)一致。


發(fā)表評論 共有條評論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 福贡县| 兴业县| 怀集县| 虞城县| 武强县| 阿巴嘎旗| 屯留县| 轮台县| 同仁县| 临武县| 灵川县| 海晏县| 泰兴市| 泾源县| 新化县| 新乐市| 木兰县| 鹤壁市| 方山县| 泰州市| 台州市| 北宁市| 常山县| 丰原市| 北川| 汕尾市| 进贤县| 龙井市| 乌海市| 汝阳县| 黄龙县| 常宁市| 宁武县| 乡城县| 平乡县| 五指山市| 桓台县| 南昌县| 内乡县| 禹城市| 滨海县|