LeetCode HOT100 - 子集

回溯搜索

每个位置选或不选

class Solution {
public:
    vector<vector<int>> subsets(vector<int>& a) {
        int n = a.size();
        vector<vector<int>> ans;
        vector<int> tmp;
        auto dfs = [&](this auto&& self, int it) -> void{
            if (it == n) {
                ans.emplace_back(tmp);
                return;
            }
            self(it + 1);
            tmp.emplace_back(a[it]);
            self(it + 1);
            tmp.pop_back();
        };
        dfs(0);
        return ans;
    }
};
posted @ 2026-05-09 11:32  rdcamelot  阅读(12)  评论(0)    收藏  举报