您的位置:首页 > 其它

LeetCode: Subsets

2013-04-21 11:26 288 查看
脑子有点混,少数次过

class Solution {
public:
void dfs(int cur, int n, vector<vector<int>> &ret, vector<int> &tmp, vector<int> S) {
if (cur == n) {
ret.push_back(tmp);
return;
}
dfs(cur+1, n, ret, tmp, S);
tmp.push_back(S[cur]);
dfs(cur+1, n, ret, tmp, S);
tmp.pop_back();
}
vector<vector<int> > subsets(vector<int> &S) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
sort(S.begin(), S.end());
vector<vector<int>> ret;
if (!S.size()) return ret;
vector<int> tmp;
dfs(0, S.size(), ret, tmp, S);
return ret;
}
};


C#

public class Solution {
public List<List<int>> Subsets(int[] nums) {
Array.Sort(nums);
List<List<int>> ans = new List<List<int>>();
if (nums.Length == 0) return ans;
List<int> tmp = new List<int>();
dfs(0, nums.Length, ref ans, ref tmp, nums);
return ans;
}
public void dfs(int cur, int n, ref List<List<int>> ans, ref List<int> tmp, int[] nums) {
if (cur == n) {
ans.Add(new List<int>(tmp.ToArray()));
return;
}
dfs(cur+1, n, ref ans, ref tmp, nums);
tmp.Add(nums[cur]);
dfs(cur+1, n, ref ans, ref tmp, nums);
tmp.RemoveAt(tmp.Count - 1);
}
}


View Code
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: