题目

给你一个整数数组 nums ,数组中的元素 互不相同 。返回该数组所有可能的子集(幂集)。
解集 不能 包含重复的子集。你可以按 任意顺序 返回解集。

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

思路

数组中的任意元素的无视顺序的组合可以看做是数组的一个子集,空集也是子集。
遍历所有结果,用回溯。

代码

  1. class Solution {
  2. List<List<Integer>> res = new ArrayList<>();
  3. public List<List<Integer>> subsets(int[] nums) {
  4. backtrack(nums, 0, new ArrayList<Integer>());
  5. return res;
  6. }
  7. public void backtrack(int[] nums, int begin, List<Integer> path) {
  8. res.add(new ArrayList(path));
  9. for (int i = begin; i < nums.length; i++) {
  10. path.add(nums[i]);
  11. backtrack(nums, i+1, path);
  12. path.remove(path.size() - 1);
  13. }
  14. }
  15. }