leetCode-Subsets

来源:互联网 发布:沈阳市2016年经济数据 编辑:程序博客网 时间:2024/06/03 15:18

Description:
Given a set of distinct integers, nums, return all possible subsets (the power set).

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],  []]

Solution:

public class Solution {    public List<List<Integer>> subsets(int[] S) {        List<List<Integer>> res = new ArrayList<>();        res.add(new ArrayList<Integer>());        Arrays.sort(S);        for(int i : S) {            List<List<Integer>> tmp = new ArrayList<>();            for(List<Integer> sub : res) {                List<Integer> a = new ArrayList<>(sub);                a.add(i);                tmp.add(a);            }            res.addAll(tmp);        }        return res;    }}

Better Solution:

 public List<List<Integer>> subsets(int[] nums) {    List<List<Integer>> res = new ArrayList<List<Integer>>();    if (nums == null || nums.length == 0) return res;    res.add(new ArrayList());    int len  =  nums.length;    for (int i = 0; i < len; i++){        int size  =  res.size();        for (int j = 0; j < size; j++){            ArrayList<Integer>  temp  = new ArrayList<Integer>(res.get(j));            temp.add(nums[i]);            res.add(temp);        }    }    return res;}}
原创粉丝点击