【LeetCode】78.Subsets(Medium)解题报告
题目地址:https://leetcode.com/problems/subsets/description/
题目描述:
Given a set of distinct integers, nums, return all possible subsets (the power set).
Note: The solution set must not contain duplicate subsets.
For example, If nums = [1,2,3], a solution is:
[
[3],
[1],
[2],
[1,2,3],
[1,3],
[2,3],
[1,2],
[]
]
给的集合里面也没有重复数字。模板backtracking。
Solutions:
class Solution {
public List<List<Integer>> subsets(int[] nums) {
List<List<Integer>> res = new ArrayList<>();
List<Integer> temp = new ArrayList<>();
if(nums.length==0 || nums == null) return res;
helper(res,temp,nums,0);
return res;
}
public void helper(List<List<Integer>> res,List<Integer> temp,int[] nums,int index){
//要加上new ArrayList<>()
res.add(new ArrayList<>(temp));
for(int i=index;i<nums.length;i++){
temp.add(nums[i]);
helper(res,temp,nums,i+1);
temp.remove(temp.size()-1);
}
}
}
Date:2018年1月3日