dimanche 25 août 2019

why I have 0 in my result? I don't know where it comes

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;
}

This code tries to find the power set of {1,2,3}, but this code has problems. First, I do the debugging print: () (1, ) (2, ) (1, 2, ) (3, ) (1, 3, ) (2, 3, ) (1, 2, 3, ) (0, )... why I have 0 here? Thank you!

Aucun commentaire:

Enregistrer un commentaire