leetcode 力扣 78 子集

52 阅读1分钟

回溯

lc78.jpeg

class Solution {
    List<Integer> path = new ArrayList<>();
    List<List<Integer>> res = new ArrayList<>();

    public List<List<Integer>> subsets(int[] nums) {
        dfs(0, nums);
        return res;
    }

    void dfs(int i, int[] nums) {
        res.add(new ArrayList<>(path));

        for (int j = i; j < nums.length; j++) {
            path.add(nums[j]);
            dfs(j + 1, nums);
            path.remove(path.size() - 1);
        }
    }
}