Leetcode: Subsets

向右看齐 2022-08-07 16:53 244阅读 0赞

题目:
Given a set of distinct integers, S, return all possible subsets.

Note:

  1. Elements in a subset must be in non-descending order.
  2. The solution set must not contain duplicate subsets.

For example,
If S = [1,2,3], a solution is:

  1. [
  2. [3],
  3. [1],
  4. [2],
  5. [1,2,3],
  6. [1,3],
  7. [2,3],
  8. [1,2],
  9. []
  10. ]

思路一:
采用深度优先搜索

  1. class Solution
  2. {
  3. private:
  4. vector<vector<int>> result;
  5. int maxDepth;
  6. private:
  7. //深度优先搜索
  8. //depth控制搜索的深度,previous是前一次搜索的结果,orgin是原始集合,start表示在origin中开始索引
  9. void dfs(int depth, vector<int> previous, vector<int> &origin, int start)
  10. {
  11. result.push_back(previous);//将前一次的结果加入最终结果集合
  12. if (depth > maxDepth) return;//如果大于最大深度,则退出
  13. for (int i = start; i < maxDepth; ++i)
  14. {
  15. vector<int> current(previous);
  16. current.push_back(origin[i]);
  17. dfs(depth + 1, current, origin, i + 1);
  18. }
  19. }
  20. public:
  21. vector<vector<int>> subsets(vector<int> &S)
  22. {
  23. maxDepth = int(S.size());
  24. result.clear();
  25. if (0 == maxDepth) return result;
  26. sort(S.begin(), S.end());
  27. vector<int> current;
  28. dfs(0, current, S, 0);
  29. return result;
  30. }
  31. };

思路二:
在网络上看到这样一种思路,觉得很巧妙。对于数组中的一个数:要么存在于子集中,要么不存在。
则有下面的代码:

  1. class Solution
  2. {
  3. private:
  4. vector<vector<int>> result;
  5. int maxDepth;
  6. void dfs(int depth, vector<int> current, vector<int> &origin)
  7. {
  8. if (depth == maxDepth)
  9. {
  10. result.push_back(current);
  11. return;
  12. }
  13. dfs(depth + 1, current, origin);//子集中不存在origin[depth]
  14. current.push_back(origin[depth]);
  15. dfs(depth + 1, current, origin);//子集中存在origin[depth]
  16. }
  17. public:
  18. vector<vector<int>> subsets(vector<int> &S)
  19. {
  20. maxDepth = int(S.size());
  21. result.clear();
  22. if (0 == maxDepth) return result;
  23. sort(S.begin(), S.end());
  24. vector<int> current;
  25. dfs(0, current, S);
  26. return result;
  27. }
  28. };

发表评论

表情:
评论列表 (有 0 条评论,244人围观)

还没有评论,来说两句吧...

相关阅读