Given a set of distinct integers, S, return all possible subsets. Note: Elements in a subset must be in non-descending order. The solution set must not contain duplicate subsets. For example, If S = [1,2,3], a solution is:
privatevoidsubset_helper(ArrayList<ArrayList<Integer>> subsets, ArrayList<Integer> subset, int start, int[] s){
for(int i=start;i<s.length;i++){
subset.add(s[i]);
//add new arraylist subset here
subsets.add(new ArrayList<Integer>(subset));
subset_helper(subsets, subset, i+1, s);
subset.remove(subset.size()-1);
}
}
Subsets II
Given a collection of integers that might contain duplicates, S, return all possible subsets. Note: Elements in a subset must be in non-descending order. The solution set must not contain duplicate subsets. For example, If S = [1,2,2], a solution is:
1
2
3
4
5
6
7
8
[
[2],
[1],
[1,2,2],
[2,2],
[1,2],
[]
]
Only difference is the added while loop. If completed current layer, and found the next element is the same then skip.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public ArrayList<ArrayList<Integer>> subsetsWithDup(int[] num) {
privatevoidsubset_helper(ArrayList<ArrayList<Integer>> subsets, ArrayList<Integer> subset, int start, int[] s){
for(int i=start;i<s.length;i++){
subset.add(s[i]);
//add new arraylist subset here
subsets.add(new ArrayList<Integer>(subset));
subset_helper(subsets, subset, i+1, s);
subset.remove(subset.size()-1);
while(i < s.length-1 && s[i]==s[i+1])
{i++;}
}
}
Missing Ranges
Given a sorted integer array where the range of elements are [lower, upper] inclusive, return its missing ranges. For example, given [0, 1, 3, 50, 75], lower = 0 and upper = 99, return [“2”, “4->49”, “51->74”, “76->99”].
Main idea: output accrodingly when two elements differ>=2, pay attention to edge cases.
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
public ArrayList<String> findmissingRanges(int[] num, int lower, int upper){