Subsets

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

Note:

  • Elements in a subset must be in non-descending order.
  • 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],
  []
]
Show Company Tags
Show Tags
Show Similar Problems
 
public class Solution {
    public List<List<Integer>> subsets(int[] nums) 
    {
        List<List<Integer>> result = new ArrayList<List<Integer>>();
        ArrayList<Integer> list = new ArrayList<Integer>();
        if(nums==null||nums.length==0) return result;
                Arrays.sort(nums);  

        subhelper(nums,result,list,0);
        return result;
    }
    
    public void subhelper(int[] nums, List<List<Integer>>result, ArrayList<Integer> list, int pos)
    {
        result.add(new ArrayList<Integer>(list));
        for(int i=pos;i<nums.length;i++)
        {
            list.add(nums[i]);
            subhelper(nums,result,list,i+1);
            list.remove(list.size()-1);
        }
        
    }
}

算法复杂度:O(2^n)

假设n=3时,C30+C31+C32+C33 = 8 = (1+1)^3

即(1+1)^n = 2^n

原文地址:https://www.cnblogs.com/hygeia/p/5180873.html