78. Subsets

好像没什么好办法,DFS。。

public class Solution {
    public List<List<Integer>> subsets(int[] nums) 
    {
        List<List<Integer>> res = new ArrayList<List<Integer>>();
        List<Integer> tempList = new ArrayList<>();
        res.add(tempList);
        if(nums.length == 0) return res;
        
        helper(res,nums,new ArrayList<Integer>(),0);
        return res;
    }
    
    public void helper(List<List<Integer>> res, int[] nums, List<Integer> tempList,int m)
    {

        if(nums.length > tempList.size())
        {
            for(int i = m; i < nums.length;i++)
            {
                tempList.add(nums[i]);
                res.add(new ArrayList<Integer>(tempList));
                helper(res,nums,new ArrayList<Integer>(tempList),i+1);
                tempList.remove(tempList.size()-1);
            }
        }
    }
}

backtrack类的一种典型。。

具体总结看这个
(https://discuss.leetcode.com/topic/46159/a-general-approach-to-backtracking-questions-in-java-subsets-permutations-combination-sum-palindrome-partitioning/2)


这算是三刷了吧。。

DFS+BACKTRACK的一种。

一般三步:
1)改变数据
2)go next level
3)恢复数据

这个是改变前要添加一下,因为是子集。。

重点
重点是如何时间和空间复杂度。以前刷没注意……
这里的问题是
某一次的时间是T(n) = T(n-1) + T(n-2) + ... + T(1)
而T(n-1) = T(n-2) + T(n-3) + ... + T(1)
所以T(n) = 2T(n-1) = 4T(n-2) = 8T(n-3)... 2^n T(1) = 2^n...

然后总体时间是 2^nT(1) + O(n), 所以最后是
Time: O(n 2^n)
space: O(n)

似乎是这样。。

recursion:

public class Solution {
    public List<List<Integer>> subsets(int[] nums) {
        List<List<Integer>> res = new ArrayList<List<Integer>>();
        dfs(res, nums, 0, new ArrayList<Integer>());
        return res;
    }
    
    public void dfs(List<List<Integer>> res, int[] nums, int m, List<Integer> tempList) {
        res.add(new ArrayList<>(tempList));
        for (int i = m; i < nums.length; i++) {
            tempList.add(nums[i]);
            dfs(res, nums, i+1, new ArrayList<>(tempList));
            tempList.remove(tempList.size() - 1);
        }
    }
}

iter:

Time: O(n 2^n)
Space: O(n)

public class Solution {
    public List<List<Integer>> subsets(int[] nums) {
        List<List<Integer>> res = new ArrayList<List<Integer>>();
        res.add(new ArrayList<>());
        int m = 0;
        for (int i = 0; i < nums.length; i++) {
            int total = res.size();
            for (int j = 0; j < total; j++) {
                List<Integer> tempList = new ArrayList<>(res.get(j));
                tempList.add(nums[i]);
                res.add(tempList);
            }
        }
        return res;
    }
}
posted @ 2016-11-07 10:50  哇呀呀..生气啦~  阅读(90)  评论(0)    收藏  举报