您的位置:首页 > 其它

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>> 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;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: