• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
ying_vincent
博客园    首页    新随笔    联系   管理    订阅  订阅

LeetCode: Subsets

脑子有点混,少数次过

 1 class Solution {
 2 public:
 3     void dfs(int cur, int n, vector<vector<int>> &ret, vector<int> &tmp, vector<int> S) {
 4         if (cur == n) {
 5             ret.push_back(tmp);
 6             return;
 7         }
 8         dfs(cur+1, n, ret, tmp, S);
 9         tmp.push_back(S[cur]);
10         dfs(cur+1, n, ret, tmp, S);
11         tmp.pop_back();
12     }
13     vector<vector<int> > subsets(vector<int> &S) {
14         // Start typing your C/C++ solution below
15         // DO NOT write int main() function
16         sort(S.begin(), S.end());
17         vector<vector<int>> ret;
18         if (!S.size()) return ret;
19         vector<int> tmp;
20         dfs(0, S.size(), ret, tmp, S);
21         return ret;
22     }
23 };

 C#

 1 public class Solution {
 2     public List<List<int>> Subsets(int[] nums) {
 3         Array.Sort(nums);
 4         List<List<int>> ans = new List<List<int>>();
 5         if (nums.Length == 0) return ans;
 6         List<int> tmp = new List<int>();
 7         dfs(0, nums.Length, ref ans, ref tmp, nums);
 8         return ans;
 9     }
10     public void dfs(int cur, int n, ref List<List<int>> ans, ref List<int> tmp, int[] nums) {
11         if (cur == n) {
12             ans.Add(new List<int>(tmp.ToArray()));
13             return;
14         }
15         dfs(cur+1, n, ref ans, ref tmp, nums);
16         tmp.Add(nums[cur]);
17         dfs(cur+1, n, ref ans, ref tmp, nums);
18         tmp.RemoveAt(tmp.Count - 1);
19     }
20 }
View Code

 

posted @ 2013-04-21 11:26  ying_vincent  阅读(139)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3