LeetCode 78. Subsets

Given an integer array nums of unique elements, return all possible subsets (the power set).

The solution set must not contain duplicate subsets. Return the solution in any order.

Example 1:

Input: nums = [1,2,3]
Output: [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]

Example 2:

Input: nums = [0]
Output: [[],[0]]

Constraints:

1 <= nums.length <= 10
-10 <= nums[i] <= 10
All the numbers of nums are unique.

实现思路:

乍一看有点像全排列,但是又不同,因为元素递增方式是1 12 123 2 23 3,
逐步递增,用暴力方式就像是双循环,本题依旧是个回溯的题目,采用基本的回溯模型就很容易做出本题。

AC代码:

class Solution {
		vector<vector<int>> ans;
		vector<int> sq;
	public:
		void dfs(vector<int> &nums,int idx) {
			ans.push_back(sq);//这一块是关键 第一个答案为空
			if(idx+1==nums.size())
				return;

			for(int i=idx+1; i<nums.size(); i++) {
				sq.push_back(nums[i]);
				dfs(nums,i);
				sq.pop_back();
			}
		}

		vector<vector<int>> subsets(vector<int>& nums) {
			dfs(nums,-1);
			return ans;
		}
};
posted @ 2021-03-04 13:33  coderJ_ONE  阅读(27)  评论(0编辑  收藏  举报