leetcode(78)子集
子集
解题思路:递归+红色区域的写法很重要,在这里要千万注意
class Solution { public List<List<Integer>> subsets(int[] nums) { List<Integer[]> result = new ArrayList<Integer[]>(); List<List<Integer>> resultList = new ArrayList<List<Integer>>(); int len = nums.length; subsets2(result,nums,len); for(Integer[] i : result){ resultList.add(Arrays.asList(i)); } return resultList; } public void subsets2(List<Integer[]> result, int[] nums, int len) { if(len==0){ Integer[] ele = new Integer[len]; result.add(ele); return; } subsets2(result, nums, len - 1); Integer[] ele = null; Integer[] temp = null; int size = result.size(); for(int i=0;i<size;++i){ temp = result.get(i); ele = new Integer[temp.length+1]; System.arraycopy(temp,0,ele,0,temp.length); ele[temp.length] = nums[len-1]; result.add(ele); } } }
第二种方法:用List不用数组
class Solution { public List<List<Integer>> subsets(int[] nums) { List<List<Integer>> result = new ArrayList<List<Integer>>(); int len = nums.length; subsets2(result,nums,len); return result; } public void subsets2(List<List<Integer>> result, int[] nums, int len) { if(len==0){ List<Integer> ele = new ArrayList<Integer>(); result.add(ele); return; } subsets2(result, nums, len - 1); List<Integer> ele = null; List<Integer> temp = null; int size = result.size(); for(int i=0;i<size;++i){ temp = result.get(i); ele = new ArrayList<Integer>(temp); ele.add(nums[len-1]); result.add(ele); } } }