思路:
DFS,时间复杂度O(2^n),空间复杂度O(n)
DFS有两种路径可以选择:
method one是先选;method two是先往下走;
c++ code:
class Solution {
private:
//Subsets : DFS
void dfs(const vector<int> &nums, int depth, vector<int> &path, vector<vector<int>> &res) {
if(depth == nums.size()) {
res.push_back(path);
return;
}
//method two
/*
//not select the element, go deep
dfs(nums,depth+1,path,res);
//select the element
path.push_back(nums[depth]);
dfs(nums,depth+1,path,res);
path.pop_back();
*/
//method one
path.push_back(nums[depth]);
dfs(nums,depth+1,path,res);
path.pop_back();
dfs(nums, depth+1, path, res);
}
public:
vector<vector<int>> subsets(vector<int>& nums) {
sort(nums.begin(),nums.end());
vector<vector<int>> res;
vector<int> path;
dfs(nums,0,path,res);
return res;
}
};
java code:
public class Solution {
public List<List<Integer>> subsets(int[] nums) {
List<List<Integer>> res = new ArrayList<List<Integer>>();
List<Integer> path = new ArrayList<>();
if(nums.length == 0) return res;
Arrays.sort(nums);
dfs(res, path, nums, 0);
return res;
}
private void dfs(List<List<Integer>> res, List<Integer> path, int[] nums, int index) {
res.add(new ArrayList<Integer>(path));
for(int i = index; i < nums.length; ++i) {
path.add(nums[i]);
dfs(res, path, nums, i + 1);
path.remove(path.size() - 1);
}
}
}