Leetcode78. 子集

139 阅读1分钟

要求:

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

示例:

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

思路:

回溯算法:

  • 添加进去的元素从0开始不断递增,符合数量要求的就添加
  • 元素数够之后回溯,其实就是不断的踢出之前添加进去的元素,再天添加新的元素

代码:

class Solution {
    List<List<Integer>> res = new ArrayList<>();
    int n,k;
    
    public List<List<Integer>> subsets(int[] nums) {
        n = nums.length;
        for (k=0; k<n+1; k++) {
            backTrack(0, new ArrayList<>(), nums);
        }
        return res;
    }
    
    public void backTrack(int start, ArrayList<Integer> cur, int[] nums) {
        if (k == cur.size()) {
            res.add(new ArrayList<>(cur));
        }
        for (int i = start, i < n; i++) {
            cur.add(nums[i]);
            backTrack(i+1, cur, nums);
            cur.remove(cur.size()-1);
        }
    }
}