[leetcode]78

子集的规律:1,2,3
空集
添加1,形成(空集)-->1
添加2,形成(空集),(1),--> (2),(1,2)
添加3,形成(空集),(1),(2),(1,2)--->(3),(1,3),(2,3),(1,2,3)

class Solution {
public:
    vector> subsets(vector& nums) {
        vector< vector > subset;
        vector empty;
        subset.push_back(empty);//空集

        for (int i = 0; i < nums.size(); i++)//对于集合中的每一个元素
        {
            vector< vector > subsetTemp = subset;
            //对于当前的子集,添加进当前的元素
            for (int j = 0; j < subsetTemp.size(); j++)
                subsetTemp[j].push_back(nums[i]);
            //将添加后的子集再添加到子集中去
            for (int j = 0; j < subsetTemp.size(); j++)
                subset.push_back(subsetTemp[j]);
        }
        return subset;
    }
};
Runtime: 4 ms, faster than 97.62% of C++ online submissions for Subsets.
Memory Usage: 9.1 MB, less than 91.53% of C++ online submissions for Subsets.

你可能感兴趣的:([leetcode]78)