标签:remove subsets last streaming ret private lis log art
class Solution { public List<List<Integer>> subsets(int[] nums) { List<List<Integer>> result = new ArrayList<>(); result.add(new ArrayList<>()); if (nums.length == 0) { return result; } for (int num : nums) { List<List<Integer>> newResult = new ArrayList<>(result); for (List<Integer> row : result) { List<Integer> newRow = new ArrayList<>(row); newRow.add(num); newResult.add(newRow); } result = newResult; } return result; } }
For streaming processing, we could use number to set as recorder of last state.
class Solution { public List<List<Integer>> subsets(int[] nums) { List<List<Integer>> result = new ArrayList<>(); long recorder = 0; long bound = (1 << nums.length) - 1; while (recorder <= bound) { result.add(toNum(recorder++, nums)); } return result; } private List<Integer> toNum(long recorder, int[] nums) { List<Integer> result = new ArrayList<>(); int i = nums.length - 1; while (i >= 0) { if ((recorder & 1L) == 1L) { result.add(nums[i]); } recorder >>= 1; i--; } return result; } }
Normal recursion:
class Solution { public List<List<Integer>> subsets(int[] nums) { List<List<Integer>> result = new ArrayList<>(); result.add(new ArrayList<>()); helper(result, 0, new ArrayList<>(), nums); return result; } private void helper(List<List<Integer>> result, int start, List<Integer> current, int[] nums) { if (start == nums.length) { return; } for (int i = start; i < nums.length; i++) { current.add(nums[i]); result.add(new ArrayList<>(current)); helper(result, i + 1, current, nums); current.remove(current.size() - 1); } } }
标签:remove subsets last streaming ret private lis log art
原文地址:http://www.cnblogs.com/shuashuashua/p/7411119.html