|
10 | 10 | */
|
11 | 11 | public class ProblemsMedium_11 {
|
12 | 12 | public static void main(String[] args) {
|
13 |
| - int[][] matrix = {{1, 3, 5, 7}, {10, 11, 16, 20}, {23, 30, 34, 50}}; |
14 |
| - System.out.println(searchMatrix(matrix, 3)); |
| 13 | +// int[][] matrix = {{1, 3, 5, 7}, {10, 11, 16, 20}, {23, 30, 34, 50}}; |
| 14 | +// System.out.println(searchMatrix(matrix, 3)); |
| 15 | + int[] nums = new int[]{1, 2, 2}; |
| 16 | + System.out.println(subsetsWithDup(nums)); |
15 | 17 | }
|
16 | 18 |
|
17 | 19 | /**
|
@@ -204,4 +206,42 @@ public List<Integer> grayCode(int n) {
|
204 | 206 | }
|
205 | 207 | return next;
|
206 | 208 | }
|
| 209 | + |
| 210 | + /** |
| 211 | + *leetcode 90 子集 |
| 212 | + * |
| 213 | + * 给定一组不含重复元素的整数数组 nums,返回该数组所有可能的子集(幂集)。 |
| 214 | + * |
| 215 | + * 说明:解集不能包含重复的子集。 |
| 216 | + * @param nums |
| 217 | + * @return |
| 218 | + */ |
| 219 | + public static List<List<Integer>> subsetsWithDup(int[] nums) { |
| 220 | + List<List<Integer>> resultList = new ArrayList<>(); |
| 221 | + if (nums == null || nums.length == 0) { |
| 222 | + return resultList; |
| 223 | + } |
| 224 | + // 首先得排序 |
| 225 | + Arrays.sort(nums); |
| 226 | + helper(resultList, new ArrayList<>(), 0, nums); |
| 227 | + return resultList; |
| 228 | + } |
| 229 | + |
| 230 | + public static void helper(List<List<Integer>> resultList, List<Integer> tmp, int start, int[] |
| 231 | + nums) { |
| 232 | + if (start <= nums.length) { |
| 233 | + resultList.add(new ArrayList<>(tmp)); |
| 234 | + } |
| 235 | + |
| 236 | + for (int i = start; i < nums.length; i++) { |
| 237 | + // i > start是关键,说明已经添加一轮到resultList里面了并出栈了,这一轮是重复的 |
| 238 | + if (i > start && nums[i] == nums[i - 1]) { |
| 239 | + continue; |
| 240 | + } |
| 241 | + tmp.add(nums[i]); |
| 242 | + //注意这里是i+1,否则i为1,start回归0的时候,再进入helper start+1还是为1,会造成重复计算 |
| 243 | + helper(resultList, tmp, i + 1, nums); |
| 244 | + tmp.remove(tmp.size() - 1); |
| 245 | + } |
| 246 | + } |
207 | 247 | }
|
0 commit comments