题目
给你一个整数数组 nums ,数组中的元素 互不相同 。返回该数组所有可能的子集(幂集)。
解集 不能 包含重复的子集。你可以按 任意顺序 返回解集。
示例 1:
输入:nums = [1,2,3]
输出:[[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]
思路
数组中的任意元素的无视顺序的组合可以看做是数组的一个子集,空集也是子集。
遍历所有结果,用回溯。
代码
class Solution {List<List<Integer>> res = new ArrayList<>();public List<List<Integer>> subsets(int[] nums) {backtrack(nums, 0, new ArrayList<Integer>());return res;}public void backtrack(int[] nums, int begin, List<Integer> path) {res.add(new ArrayList(path));for (int i = begin; i < nums.length; i++) {path.add(nums[i]);backtrack(nums, i+1, path);path.remove(path.size() - 1);}}}
