import java.util.ArrayList;
import java.util.List;
/**
* leetcode 78 子集
* https://leetcode-cn.com/problems/subsets/
*/
public class DayCode {
public static void main(String[] args) {
int[] nums = new int[]{1,2,3};
List<List<Integer>> ans = new DayCode().subSets(nums);
}
public List<List<Integer>> subSets(int[] nums) {
List<List<Integer>> ans = new ArrayList<>();
if (nums == null) {
return ans;
}
List<Integer> item = new ArrayList<>();
dfs(nums, 0, ans, item);
return ans;
}
private void dfs(int[] nums, int index, List<List<Integer>> ans, List<Integer> item) {
if (index == nums.length) {
ans.add(new ArrayList<>(item));
return;
}
dfs(nums, index + 1, ans, item);
item.add(nums[index]);
dfs(nums, index + 1, ans, item);
item.remove(item.size()-1);
}
}
评论