给定一个整数数组 nums ,数组中的元素 互不相同 。返回该数组所有可能的子集(幂集)。
解集 不能 包含重复的子集。你可以按 任意顺序 返回解集。
示例 1:
输入:nums = [1,2,3]
输出:[[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]
示例 2:
输入:nums = [0]
输出:[[],[0]]
利用回溯法解题:到达最后一位后,回溯到上一位
class Solution { public List<List<Integer>> subsets(int[] nums) { List<List<Integer>> result = new ArrayList<>(); List<Integer> list = new ArrayList<>(); dfs(nums, 0, list, result, false); return result; } public void dfs(int[] nums, int curIndex, List<Integer> list, List<List<Integer>> result, boolean flag) { //达到最后一位 if (curIndex > nums.length - 1) { List<Integer> list2 = new ArrayList<>(list); result.add(list2); //弹出 if (list.size() > 0 && flag) { list.remove(list.size() - 1); } return; } //不选当前节点 dfs(nums, curIndex + 1, list, result, false); //选当前节点 list.add(nums[curIndex]); dfs(nums, curIndex + 1, list, result, true); //弹出 if (list.size() > 0 && flag) { list.remove(list.size() - 1); } } }