78. Subsets

来源:互联网 发布:程序员入门知识 编辑:程序博客网 时间:2024/06/06 21:51
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],  []]
这种问题应该从小规模的开始解决。比如只有两个数字{1,2}的时候,那么子集:{[],[1],[2].[1,2]},加入3的时候相当于保留原来的所有的元素,并加入所有元素加上一个3::{[],[1],[2].[1,2],[3],[1,3],[2,3],[1,2,3]},再加上元素的时候类推。从{}到{1}和{1}到{1,2}其实也是如此。所以只要写一个子函数,子集一开始只有{[]},后来每次添加一个元素直到遍历结束。
注意这里取ArrayList<List<Integer>>中的每个对象加入新的数字的时候要new一个新的对象,不然就是对原来的进行修改了,因为传递的是对象。
class Solution {public List<List<Integer>> subsets(int[] nums) {        List<List<Integer>> res = new ArrayList<>();        if(nums.length==0)            return res;        res.add(new ArrayList<Integer>());        for(int i=0;i<nums.length;i++){        generateSub(res, nums[i]);        System.out.println("1111");        }        return res;    }public void generateSub(List<List<Integer>> res, int temp){System.out.println("temp:"+temp);int len = res.size();List<List<Integer>> last = new ArrayList<List<Integer>>(res);//注意这里要用new之后的对象,不然每次循环里面都会改变for(int i=0;i<len;i++){System.out.println("len:"+len);List<Integer> cur = new ArrayList<>(last.get(i));//这里也是要new一个对象,不然就是直接改原来的对象System.out.println("cur:"+cur);cur.add(temp);res.add(cur);}}}


回溯法解决:
public List<List<Integer>> subsets(int[] nums) {    List<List<Integer>> list = new ArrayList<>();    Arrays.sort(nums);    backtrack(list, new ArrayList<>(), nums, 0);    return list;}private void backtrack(List<List<Integer>> list , List<Integer> tempList, int [] nums, int start){    list.add(new ArrayList<>(tempList));    //注意这里也new 了新的对象    for(int i = start; i < nums.length; i++){        tempList.add(nums[i]);        backtrack(list, tempList, nums, i + 1);        tempList.remove(tempList.size() - 1);    }}

 
原创粉丝点击