随笔- 509  文章- 0  评论- 151  阅读- 22万 

Subsets

2013.12.26 15:19

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],
  []
]
复制代码

Solution:

  The mathematical definition of a set ensures the uniqueness of its elements. For a set of cardinality n, the number of its subsets is 2^n. A DFS will traverse every one of them. During each recursion, you can either choose this element or not, resulting in two recursive path.

  Time complexity is O(2^n), where n is the cardinality of the set. Space complexity is O(n).

Accepted code:

复制代码
 1 // 2CE, 1OLE, 1RE, 4WA, 1AC, so difficult...
 2 class Solution {
 3 public:
 4     vector<vector<int> > subsets(vector<int> &S) {
 5         // IMPORTANT: Please reset any member data you declared, as
 6         // the same Solution instance will be reused for each test case.
 7         int i, n;
 8         
 9         n = result.size();
10         for(i = 0; i < n; ++i){
11             result[i].clear();
12         }
13         result.clear();
14         // 1WA here, S is not sorted, thus need sorting to ensure that the result is sorted
15         sort(S.begin(), S.end());
16         arr.clear();
17         n = S.size();
18         // 1CE here, ; is missing after dfs
19         dfs(0, n, S);
20         
21         return result;
22     }
23 private:
24     vector<vector<int>> result;
25     vector<int> arr;
26     
27     // 1CE here, S is not declared in this scope
28     void dfs(int idx, int n, vector<int> &S) {
29         // 1RE here, didn't check n, out of range
30         // 1WA here, only push result when idx == n, or else would have redundant results.
31         if(idx == n){
32             result.push_back(arr);
33             return;
34         }
35         
36         // 1OLE here, for(i = idx; i < n; ++i) structure is wrong, need no for
37         dfs(idx + 1, n, S);
38         arr.push_back(S[idx]);
39         dfs(idx + 1, n, S);
40         arr.pop_back();
41     }
42 };
复制代码

 

 posted on   zhuli19901106  阅读(892)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)
点击右上角即可分享
微信分享提示