leetcode:78. 子集
学习要点
首先就是要先明白什么是回溯:leetcode:46. 全排列-CSDN博客。在此基础上我们可以细化一下这种题的解题思路。
题目链接
78. 子集 - 力扣(LeetCode)
题目描述
解法:回溯
class Solution {
public:vector<vector<int>> ret;vector<int> path;void dfs(vector<int>& nums,int pos){for(int i =pos;i<nums.size();i++){path.push_back(nums[i]); ret.push_back(path);dfs(nums,i+1);path.pop_back();}}vector<vector<int>> subsets(vector<int>& nums) {ret.clear(); ret.push_back(vector<int>());dfs(nums,0);return ret;}
};
解析
- 首先要了解回溯算法,上文附有链接
- 先添加子集中有v[0]的
- 再添加子集中有v[1]但是没有v[0]的
- 再添加子集中有v[2]但是没有v[0]和v[1]的
- 以此类推