【LeetCode】78. Subsets

题目:

Given a set of distinct integers, nums, return all possible subsets (the power set).

Note: The solution set must not contain duplicate subsets.

Example:

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

描述:

给出一个数组,输出该数组的全部子集,

 

分析:

递归暴力求解,

本题目可以分解为多道求组合的题目(解法点这里),

对于本题来说,数组中的数据不一定是增序,想要控制组合的生成需要多加一个标识位,具体看代码实现...

 

代码:

class Solution {
public:
	vector<vector<int>> subsets(vector<int>& nums) {
		
		vector<vector<int>> result;
		
		for (int i = 0; i <= nums.size(); ++ i) {
			vector<bool> visit(nums.size(), false);
			vector<int> current;
			dfs(i, 0, nums, visit, current, result);
		}
		
		return result;
	}
	void dfs(int k, int index, const vector<int> &nums, vector<bool> &visit, vector<int> &current, vector<vector<int>> &result) {
		if (!k) {
			result.push_back(current);
			return ;
		}
		
		for (int i = index; i < nums.size(); ++ i) {
			if (!visit[i]) {
				visit[i] = 1;
				if (!current.size() || i >= current.size()) {
					current.push_back(nums[i]);
					dfs(k - 1, i, nums, visit, current, result);
					current.pop_back();
				}
				visit[i] = 0;
			}
		}
	}
};

 

©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页