-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSubsetSum_II_GFG.java
More file actions
67 lines (61 loc) · 2.04 KB
/
Copy pathSubsetSum_II_GFG.java
File metadata and controls
67 lines (61 loc) · 2.04 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
package RecursionAndBacktracking;
import java.util.*;
/**
* LeetCode link : https://leetcode.com/problems/subsets-ii/
* Given an integer array nums that may contain duplicates, return all possible subsets (the power set).
*
* The solution set must not contain duplicate subsets. Return the solution in any order.
*
*
*
* Example 1:
*
* Input: nums = [1,2,2]
* Output: [[],[1],[1,2],[1,2,2],[2],[2,2]]
* Example 2:
*
* Input: nums = [0]
* Output: [[],[0]]
*
*
* Constraints:
*
* 1 <= nums.length <= 10
* -10 <= nums[i] <= 10
*/
public class SubsetSum_II_GFG {
public static void subsets(int index, int[] array, int sizeOfArray, List<List<Integer>> ans, ArrayList<Integer> ds){
// adding null list
ans.add(new ArrayList<>(ds));
// running loop from index to size-1
// for adding other valid subsets
for(int i=index ; i<sizeOfArray ; i++){
// condition for duplicate element
if(i>index && array[i]==array[i-1]){
continue;
}
// performing recursive call
ds.add(array[i]);
subsets(i+1, array, sizeOfArray, ans, ds);
ds.remove(ds.size()-1);
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number of testcases:");
int numberOfTestcases = sc.nextInt();
while (numberOfTestcases-- > 0){
System.out.println("Enter the size of the array:");
int sizeOfArray = sc.nextInt();
System.out.println("Enter the elements of the array:");
int[] array = new int[sizeOfArray];
for(int index=0 ; index<sizeOfArray ; index++){
array[index] = sc.nextInt();
}
List<List<Integer>> ans = new ArrayList<>();
subsets(0, array, sizeOfArray, ans, new ArrayList<>());
Arrays.sort(array);
System.out.println(ans);
}
}
}