78.90 Subsets

来源:互联网 发布:js trigger事件 编辑:程序博客网 时间:2024/06/05 18:05

Given a set of distinct integers, nums, return all possible subsets.

Note: The solution set must not contain duplicate subsets.

For example,
If nums = [1,2,3], a solution is:

[  [3],  [1],  [2],  [1,2,3],  [1,3],  [2,3],  [1,2],  []]


回溯法

代码:

<span style="font-size:14px;"><span style="font-size:14px;">public class Solution {    public List<List<Integer>> subsets(int[] nums) {        List<List<Integer>> result=new ArrayList<List<Integer>>();        subHelp(0,result,new ArrayList<Integer>(),nums);        return result;    }        public void subHelp(int start,List<List<Integer>> result,List<Integer> list,int[] nums){        result.add(new ArrayList<Integer>(list));        for(;start<nums.length;start++){            list.add(nums[start]);            subHelp(start+1,result,list,nums);            list.remove(list.size()-1);        }    }   }</span></span>

Given a collection of integers that might contain duplicates,nums, return all possible subsets.

Note: The solution set must not contain duplicate subsets.

For example,
If nums = [1,2,2], a solution is:

[  [2],  [1],  [1,2,2],  [2,2],  [1,2],  []]

先对数组排序,遇见重复的则跳过。

<span style="font-size:14px;">public class Solution {    public List<List<Integer>> subsetsWithDup(int[] nums) {        List<List<Integer>> res=new ArrayList<List<Integer>>();        Arrays.sort(nums);        subsetHelp(res,new ArrayList<Integer>(),0,nums);        return res;    }    public void subsetHelp(List<List<Integer>> res,List<Integer> list,int start,int[] nums){        //if(!res.contains(list))            res.add(new ArrayList<Integer>(list));        for(int i=start;i<nums.length;i++){            if(start<i&&nums[i]==nums[i-1])                continue;            list.add(nums[i]);            subsetHelp(res,list,i+1,nums);            list.remove(list.size()-1);        }            }}</span>


0 0
原创粉丝点击