yokostan / Leetcode-Solutions

Doing exercise on Leetcode. Carry on!
0 stars 3 forks source link

Leetcode #78 Subsets #119

Open yokostan opened 6 years ago

yokostan commented 6 years ago

Given a set of distinct integers, nums, return all possible subsets (the power set).

Note: The solution set must not contain duplicate subsets.

Example:

Input: nums = [1,2,3] Output: [ [3], [1], [2], [1,2,3], [1,3], [2,3], [1,2], [] ]

Solutions: class Solution { public List<List> subsets(int[] nums) { List<List> list = new ArrayList<List>(); backtracking(nums, list, new ArrayList<>(), 0); return list; } public void backtracking(int[] nums, List<List> list, List tempList, int start) { list.add(new ArrayList<>(tempList)); for (int i = start; i < nums.length; i++) { tempList.add(nums[i]); backtracking(nums, list, tempList, i + 1); tempList.remove(tempList.size() - 1); }
} }

Points:

  1. The old template, you know it.