78. Subsets (not use befroe, so int I = start, dfs(i+1)

subset: ๅ…ƒ็ด  unique, ไธไฝฟ็”จ้‡่ค‡ๆ•ธๅญ—

subset, ไธๅ…่จฑไฝฟ็”จ้‡่ค‡ๆ•ธๅญ—

with int i = start, dfs(i+1) to next level, ไธ‹ๅฑคๆŒ‘้ธ็š„ๆ•ธๅญ—ๅฟ…ๅฎšๆ˜ฏๆฒ’็”จ้Ž, ๆ‰€ไปฅไธๆœƒๆœ‰้‡่ค‡

time: O(2^n) or O(2^n*n) , the subset's count is 2^n

space: O(2^n) or O(2^n*n)

class Solution {
    public List<List<Integer>> subsets(int[] nums) {
        List<List<Integer>> res = new ArrayList<>();
        if (nums == null || nums.length == 0) return res;
        helper(res, new ArrayList<>(), nums, 0);
        return res;
    }
    // backtracking, [], [1], [2], [3], index +1 [1,2]...
    private void helper(List<List<Integer>> res, List<Integer> list, int[] nums, int index) {
        res.add(new ArrayList<>(list));
        for (int i = index; i< nums.length; i++) {
            list.add(nums[i]);
            helper(res, list, nums, i + 1);
            list.remove(list.size() - 1);
        }
    }
}

Last updated