Skip to content

Commit 7e99a87

Browse files
MEDIUM/src/medium/Subsets.java for loop way
1 parent 95dbb95 commit 7e99a87

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

MEDIUM/src/medium/Subsets.java

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
package medium;
2+
3+
import java.util.ArrayList;
4+
import java.util.List;
5+
6+
import utils.CommonUtils;
7+
8+
public class Subsets {
9+
10+
public static void main(String...strings){
11+
int[] nums = new int[]{1,2,3};
12+
List<List<Integer>> result = subsets(nums);
13+
CommonUtils.printIntegerList(result);
14+
}
15+
16+
public static List<List<Integer>> subsets(int[] nums) {
17+
List<List<Integer>> result = new ArrayList();
18+
List<Integer> empty = new ArrayList();
19+
result.add(empty);
20+
if(nums == null) return result;
21+
for(int i = 0; i < nums.length; i++){
22+
List<List<Integer>> temp = new ArrayList();//you'll have to create a new one here, otherwise, it'll throw ConcurrentModificationException.
23+
for(List<Integer> list : result){
24+
List<Integer> newList = new ArrayList(list);
25+
newList.add(nums[i]);
26+
temp.add(newList);
27+
}
28+
result.addAll(temp);
29+
}
30+
return result;
31+
}
32+
33+
}

0 commit comments

Comments
 (0)