给你一个整数数组 nums ,数组中的元素 互不相同 。返回该数组所有可能的

子集

(幂集)。

解集 不能 包含重复的子集。你可以按 任意顺序 返回解集。

 

示例 1:

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

示例 2:

输入:nums = [0]
输出:[[],[0]]

 

提示:

  • 1 <= nums.length <= 10
  • -10 <= nums[i] <= 10
  • nums 中的所有元素 互不相同

class Solution {
    List<List<Integer>> res = new ArrayList<>();
    List<Integer> path = new ArrayList<>();
    public List<List<Integer>> subsets(int[] nums) {
        // 空集合也算是一个子集
        res.add(new ArrayList<>());
        backtracking(nums,0);
        return res;
    }

    public void backtracking(int[] nums,int startIndex) {
        if (startIndex >= nums.length)return;

        for (int i = startIndex; i < nums.length; i++) {
            // 每遍历一个元素,就将该元素加入到path中,并加入到 res集合中。都算是一个子集
            path.add(nums[i]);
            res.add(new ArrayList<>(path));
            backtracking(nums,i+1);
            path.remove(path.size() -1);
        }
    }
}