LeetCode Brushing Notes_78. Subset

The topic is from LeetCode

78. Subset

Other solutions or source code can be accessed: tongji4m3

description

Given a set of integer arrays nums without repeated elements, return all possible subsets (power sets) of the array.

Note: The solution set cannot contain duplicate subsets.

Example:

输入: nums = [1,2,3]
输出:
[
  [3],
  [1],
  [2],
  [1,2,3],
  [1,3],
  [2,3],
  [1,2],
  []
]

Ideas

Draw the solution space tree, which is equivalent to adding all the elements of the solution space tree to the set (remove duplicate sets)

boolean [] marked;
recursive(0);

recursive(int height)
{
    
    
    result.add(temp);
    if(height==N) return;
    for i in N
    {
    
    
        if(!marked[i])
        {
    
    
            temp.add(nums[i]);
            marked[i]=true;
            recursive(height+1);
            marked[i]=false;
            temp.remove(nums[i]);          
              
        }
    }
}

detail

  1. Note that duplicate sets should be removed, so partial ordering can be used directly to simplify the code

Code

private List<Integer> temp = new LinkedList<>();
private List<List<Integer>> result = new LinkedList<>();

public List<List<Integer>> subsets(int[] nums)
{
    
    
    recursive(nums,0);
    return result;
}

public void recursive(int[] nums,int start)
{
    
    
    result.add(new LinkedList<>(temp));

    for (int i = start; i < nums.length; i++)
    {
    
    
        temp.add(nums[i]);
        recursive(nums,i+1);
        temp.remove(temp.size()-1);
    }
}
//循环
//本质上就是模拟一个个元素不断加入集合的过程
public List<List<Integer>> subsets(int[] nums)
{
    
    
    List<List<Integer>> result = new LinkedList<>();
    result.add(new LinkedList<>());//刚开始为空集

    for (int i = 0; i < nums.length; i++)
    {
    
    
        //加入元素nums[i]所得到的额外的list
        List<List<Integer>> list = new LinkedList<>();
        for (List<Integer> e : result)//就是通过原本的每个集合都加入该元素
        {
    
    
            List<Integer> temp = new LinkedList<>(e);
            temp.add(nums[i]);
            list.add(temp);
        }
        result.addAll(list);
    }
    return result;
}

Complexity analysis

time complexity

O (1) O (1) O ( 1 )

Space complexity

O (1) O (1) O ( 1 )

Guess you like

Origin blog.csdn.net/weixin_42249196/article/details/108354525