void ExhaustSet(const vector<int>& nums,
vector<vector<int>>& ans, int end) {
if (end == nums.size()) {
return;
}
if (end < 0) {
ans.push_back({});
ExhaustSet(nums, ans, end+1);
}
auto ans_copy = ans;
for (auto temp : ans_copy) {
temp.push_back(nums[end]);
ans.push_back(temp);
}
ExhaustSet(nums, ans, end+1);
}
vector<vector<int>> subsets(const vector<int>& nums) {
if (nums.empty()) {
return {};
}
vector<vector<int>> ans;
ExhaustSet(nums, ans, -1);
return ans;
}
int main()
{
auto ans = subsets({1,2,3});
for (const auto& e : ans) {
cout<<"(";
for (int num : e){
cout<<num<<", ";
}
cout<<")\n";
}
return 0;
}
此代码尝试查找{1,2,3}的幂集,但是此代码有问题。 首先,我进行调试打印: ()(1,)(2,)(1,2,)(3,)(1,3,)(2,3,)(1,2,3,)(0,)... 为什么我这里有0? 谢谢!
答案 0 :(得分:0)
问题出在算法的第一步,当num == -1时,它开始递归步骤:
void ExhaustSet(const vector<int>& nums,
vector<vector<int>>& ans, int end) {
if (end == nums.size()) {
return;
}
if (end < 0) {
ans.push_back({});
ExhaustSet(nums, ans, end+1);
// ** HERE YOU NEED A RETURN STATEMENT
}
auto ans_copy = ans;
for (auto temp : ans_copy) {
temp.push_back(nums[end]);
ans.push_back(temp);
}
ExhaustSet(nums, ans, end+1);
}
...因此,一旦迭代结束,您将对内端-1再执行一步,而nums [-1]则无效。
程序不会崩溃是一个奇迹。
void ExhaustSet(const vector<int>& nums,
vector<vector<int>>& ans, int end) {
if (end == nums.size()) {
return;
}
if (end < 0) {
ans.push_back({});
ExhaustSet(nums, ans, end+1);
return;
}
auto ans_copy = ans;
for (auto temp : ans_copy) {
temp.push_back(nums[end]);
ans.push_back(temp);
}
ExhaustSet(nums, ans, end+1);
}