leetcode

78.子集

力扣链接

class Solution {
public:
    std::vector<std::vector<int>> res;
    std::vector<int> path;
    // 问题未解决?? int startIndex 为什么不能用 int& startIndex
    // 错误 int& startIndex 为非常量左值引用 无法和backtracking(nums, i + 1);里的右值i+1绑定
    // 此处由于递归函数的特殊性 参数startIndex的类型要使用非引用类型
    void backtracking (std::vector<int>& nums, int startIndex){
        res.push_back(path);
        if (path.size() >= nums.size()) return; //或 if (startIndex >= nums.size()) return;
        // 错误 i = 0 开始
        for (int i = startIndex; i < nums.size(); i++){
            path.push_back(nums[i]);
            backtracking(nums, i + 1);
            path.pop_back();
        }
    }

    std::vector<std::vector<int>> subsets(std::vector<int>& nums) {
        int startIndex = 0;
        backtracking(nums, startIndex);
        return res;      
    }
};