Given a set of distinct integers, S, return all possible subsets.
Note:
- Elements in a subset must be in non-descending order.
- The solution set must not contain duplicate subsets.
For example,
If S =
[1,2,3]
, a solution is:[ [3], [1], [2], [1,2,3], [1,3], [2,3], [1,2], [] ]
题目地址: https://oj.leetcode.com/problems/subsets/ 解题思路:
这道题做了两种解法。
【leetcode做题笔记|leetcode:Subsets】解法1:
因为从S中每添加一个元素进来,下一层的集合=上一层的集合+每一个上一层的集合的后面加上新添加的那个元素。如下:
0----------[ ]
1----------[ ] [1]
2----------[ ] [1] [2] [1 2]
3----------[ ] [1] [2] [1 2] [3] [1 3] [2 3] [1 2 3]
.........
代码:
class Solution {
public:
vector > subsets(vector &S) {
sort(S.begin(),S.end());
vector > ret(1);
for(int i=0;
i tmp=ret[j];
tmp.push_back(S[i]);
ret.push_back(tmp);
}
}
return ret;
}
};
解法2: 用递归+回溯的方法,这个方法可能看代码会比较清晰。参考了别人的代码:
class Solution {
public:
vector > ret;
vector > subsets(vector &S) {
ret.clear();
sort(S.begin(),S.end());
vector tmpans;
dfs(S,0,tmpans);
return ret;
}
private:
void dfs(vector &s,int loc,vector &tmp){
if(loc==s.size()){
ret.push_back(tmp);
return;
}tmp.push_back(s[loc]);
dfs(s,loc+1,tmp);
tmp.pop_back();
dfs(s,loc+1,tmp);
}
};
推荐阅读
- 数据结构与算法|【算法】力扣第 266场周赛
- leetcode|今天开始记录自己的力扣之路
- 动态规划|暴力递归经典问题
- Python|Python 每日一练 二分查找 搜索旋转排序数组 详解
- 【LeetCode】28.实现strstr() (KMP超详细讲解,sunday解法等五种方法,java实现)
- LeetCode-35-搜索插入位置-C语言
- leetcode python28.实现strStr()35. 搜索插入位置
- Leetcode Permutation I & II
- python|leetcode Longest Substring with At Most Two Distinct Characters 滑动窗口法
- LeetCode 28 Implement strStr() (C,C++,Java,Python)