给定一组不含重复元素的整数数组 nums,返回该数组所有可能的子集(幂集)。

说明:解集不能包含重复的子集。

示例:

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

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/subsets

 

方法一: 暴力法(扩展发) 效率比较慢

  LeetCode 78. 子集_重复元素

class Solution {
    public List<List<Integer>> subsets(int[] nums) {
          List<List<Integer>> resultList = new ArrayList<List<Integer>>();
		resultList.add(new ArrayList());
		for(int num : nums){
			System.out.println(num);
			int size = resultList.size();
			for(int i=0; i<size; i++){
				ArrayList cur = new ArrayList(resultList.get(i));
				cur.add(num);
				resultList.add(cur);
			}
		}
		System.out.println(resultList);
		
		return resultList;
    }
}

LeetCode 78. 子集_java_02

 

 

 

方法二:回溯法

LeetCode 78. 子集_java_03

import java.util.ArrayList;
import java.util.List;

public class SubSets {
	public static void main(String[] args) {
		int[] nums = { 1,2,3};
		
		List<List<Integer>> res = new ArrayList<List<Integer>>();
		for(int i=0; i<nums.length+1; i++){
			backtracking(nums, i/*表示第i层*/ ,0/*每一层都从下标0开始遍历*/,res,new ArrayList()/*保存每一层的结果*/);
		}
		System.out.println(res);
	}

	/**
	 * len: 层数
	 * startIndex: 从数组哪个位置开始
	 * res:最终结果
	 * cur:保存每一层的结果
	 */ 
	private static void backtracking(int[] nums, int len, int startIndex, List<List<Integer>> res, List<Integer> cur){
			if(cur.size() == len){// 当前层len 是否等于 当前层的结果list的长度
				res.add(new ArrayList(cur));
				return;
			}
			
			for(int i=startIndex; i<nums.length; i++){
				cur.add(nums[i]);
				backtracking(nums,len,i+1,res,cur);
				cur.remove(cur.size()-1);
			}
	}

}

LeetCode 78. 子集_深度优先_04

 

方法三:深度优先dfs算法

import java.util.ArrayList;
import java.util.List;

public class Subsets {
    public static void main(String[] args) {
        int[] nums = {1, 2, 3};
        ArrayList res = new ArrayList();

        dfs(nums, 0, res, new ArrayList());

        System.out.println(res);
    }

    private static void dfs(int[] nums, int startIndex, List<List<Integer>> res, List<Integer> cur){
        res.add(new ArrayList<>(cur));

        for(int i=startIndex; i<nums.length; i++){
            cur.add(nums[i]);
            dfs(nums,i+1,res,cur);
            cur.remove(cur.size()-1);
        }
    }
}