78. 子集

2021-07-14  本文已影响0人  justonemoretry
image.png

解法

class Solution {
    public List<List<Integer>> subsets(int[] nums) {
        List<List<Integer>> res = new ArrayList<>();
        List<Integer> path = new ArrayList<>();
        backTrack(nums, 0, path, res);
        return res;
    }

    public static void backTrack(int[] nums, int startIndex, List<Integer> path, List<List<Integer>> res) {
        // 每一步都符合要求,下面的条件startIndex到了len,就不会再走了,
        // 所以这里也不用做递归结束的判断了
        res.add(new ArrayList<>(path));
        for (int i = startIndex; i < nums.length; i++) {
            path.add(nums[i]);
            backTrack(nums, i + 1, path, res);
            path.remove(path.size() - 1);
        }
    }
}
上一篇 下一篇

猜你喜欢

热点阅读