Note:
- Elements in a subset must be in non-descending order.
- The solution set must not contain duplicate subsets.
For example,
If S =
If S =
[1,2,2]
, a solution is:[ [2], [1], [1,2,2], [2,2], [1,2], [] ]
public class Solution { public ArrayList<ArrayList<Integer>> subsetsWithDup(int[] num) { ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>(); if(num.length == 0|| num == null){ return result; } ArrayList<Integer> tem = new ArrayList<Integer>(); Arrays.sort(num); dfs(result, tem, num, 0); return result; } public void dfs(ArrayList<ArrayList<Integer>> result, ArrayList<Integer> tem, int[] num, int pos){ result.add(new ArrayList<Integer> (tem)); for(int i=pos; i<num.length; i++){ if ( i != pos && num[i] == num[i - 1]) { continue; } tem.add(num[i]); dfs(result,tem,num,i+1); tem.remove(tem.size()-1); } } }1. 这道题之前一定要sort一下。
2.判重用了一个if语句
分析:
假设还用subset方法 对于[1,2,2,2]
结果是[]
[1]
[1, 2(1)]
[1, 2(1), 2(2)]
[1, 2(1), 2(2), 2(3)]
[1, 2(1), 2(3)]//把2(3)删去 再把2(2)删去,此时2(1)层没循环完, 还可以再加入2(3)
[1,2(2)]
[1,2(2),(2,3)]
.............
只关心取了几个2不在乎取哪几个
在if语句里 i!= pos, 说明pos位置的数上一次已经取过(已跳过),为了避免与已经跳过的数重复, 说以如果num[i]==num[i-1]就continue
没有评论:
发表评论