标签:art style with vat set rem || ++ add
78 nums 元素没有重复, 求subsets, 共有 2^n个
Input: nums = [1,2,3] Output: [ [3], [1], [2], [1,2,3], [1,3], [2,3], [1,2], [] ]
class Solution { public List<List<Integer>> subsets(int[] nums) { List<List<Integer>> result = new ArrayList<>(); dfs(0, new ArrayList<>(), result, nums); return result; } private void dfs(int start, List<Integer> curResult, List<List<Integer>> result, int[] nums){ result.add(new ArrayList<>(curResult)); if(curResult.size() == nums.length){ return; } for(int i=start; i<nums.length; i++){ curResult.add(nums[i]); dfs(i+1, curResult, result,nums); curResult.remove(curResult.size()-1); } } }
90. 有重复元素情况下求组合数, 唯一需要注意的是如何去重:
if(i==start || i>start && nums[i]!= nums[i-1])
Input: [1,2,2] Output: [ [2], [1], [1,2,2], [2,2], [1,2], [] ]
class Solution { public List<List<Integer>> subsetsWithDup(int[] nums) { List<List<Integer>> result = new ArrayList<>(); Arrays.sort(nums); dfs(0, new ArrayList<>(), result, nums); return result; } private void dfs(int start, List<Integer> curResult, List<List<Integer>> result, int[] nums){ result.add(new ArrayList<>(curResult)); if(curResult.size() == nums.length){ return; } for(int i=start; i<nums.length; i++){ if(i==start || i>start && nums[i]!= nums[i-1]){ curResult.add(nums[i]); dfs(i+1, curResult, result,nums); curResult.remove(curResult.size()-1); } } } }
标签:art style with vat set rem || ++ add
原文地址:https://www.cnblogs.com/keepAC/p/9938395.html