Leetcode 78. Subsets
2016-12-26 05:44
369 查看
DFS recursive solution.
public class Solution {
public List<List<Integer>> subsets(int[] nums) {
List<List<Integer>> ret = new ArrayList<>();
List<Integer> curr = new ArrayList<>();
dfs(0, nums, curr, ret);
// don't forget to add empty set into the subset
ret.add(new ArrayList<>(curr));
return ret;
}
private static void dfs(int pos, int[] nums, List<Integer> curr, List<List<Integer>> ret) {
for (int i=pos; i<nums.length; i++) {
curr.add(nums[i]);
ret.add(new ArrayList<>(curr));
// the next starting position is i+1 (*)
dfs(i+1, nums, curr, ret);
curr.remove(curr.size()-1);
}
}
}Iteration solution.
public class Solution {
public List<List<Integer>> subsets(int[] nums) {
List<List<Integer>> ret = new ArrayList<>();
List<Integer> curr = new ArrayList<>();
dfs(0, nums, curr, ret);
// don't forget to add empty set into the subset
ret.add(new ArrayList<>(curr));
return ret;
}
private static void dfs(int pos, int[] nums, List<Integer> curr, List<List<Integer>> ret) {
for (int i=pos; i<nums.length; i++) {
curr.add(nums[i]);
ret.add(new ArrayList<>(curr));
// the next starting position is i+1 (*)
dfs(i+1, nums, curr, ret);
curr.remove(curr.size()-1);
}
}
}Iteration solution.
public class Solution { public List<List<Integer>> subsets(int[] nums) { List<List<Integer>> res = new ArrayList<>(); res.add(new ArrayList<Integer>()); //Arrays.sort(nums); for (int num : nums) { // using tmp list to avoid ConcurrentModificationException (*) List<List<Integer>> tmp = new ArrayList<>(); for (List<Integer> sub : res) { List<Integer> a = new ArrayList(sub); a.add(num); tmp.add(a); } res.addAll(tmp); } return res; } }
相关文章推荐
- Leetcode_78_Subsets
- LeetCode 78: Subsets
- LeetCode_OJ【78】Subsets
- leetcode_middle_58_78. Subsets
- leetcode_77_combiantion_78_subsets_90_subsets2
- (LeetCode 78)SubSets
- <LeetCode OJ> 78 / 90 Subsets (I / II)
- LeetCode 78. Subsets
- leetcode: 78. Subsets
- LeetCode(78) Subsets
- Leetcode 78. Subsets
- LeetCode(78) Subsets
- LeetCode78 Subsets
- LeetCode 78: Subsets
- Leetcode 78. Subsets & 90. Subsets II
- Leetcode 78. Subsets
- Leetcode 78 Subsets
- [LeetCode] 78. Subsets
- [leetcode]78. Subsets
- LeetCode 78 Subsets