LeetCode Subsets

LeetCode Subsets

Given a set of distinct integers, nums, return all possible subsets.

Note: The solution set must not contain duplicate subsets.

For example,
If nums = [1,2,3], a solution is:

[
  [3],
  [1],
  [2],
  [1,2,3],
  [1,3],
  [2,3],
  [1,2],
  []
]

求一个集合的所有子集,高中就知道所有子集个数为2^n个,包括空集和它本身。

算法思路和LeetCode Combinations几乎一样,只不过成功条件不再是candidate中有k个数了,而是每添加一个元素都算成功一个。

完整代码如下:

class Solution {
public:
	void work(vector<vector<int>>& ans, vector<int>& cand, vector<int>& nums, int step) {
		ans.push_back(cand);
		for (int i = step; i < nums.size(); i++) {
			cand.push_back(nums[i]);
			work(ans, cand, nums, i + 1);
			cand.pop_back();
		}
	}
	vector<vector<int>> subsets(vector<int>& nums) {
		vector<vector<int>> ans;
		vector<int> cand;
		work(ans, cand, nums, 0);
		return ans;
	}
};

本代码提交AC,用时3MS。

One thought on “LeetCode Subsets

  1. Pingback: LeetCode Subsets II | bitJoy > code

Leave a Reply

Your email address will not be published. Required fields are marked *