LeetCode-Subsets-解题报告

原创 2015年07月08日 19:59:25

原题链接 https://leetcode.com/problems/subsets/

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

Note:

  • Elements in a subset must be in non-descending order.
  • 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],
  []
]

使用回溯法即可。


class Solution {
public:
    vector<vector<int> > subsets(vector<int>& nums) {
		vector <vector<int> >ans;
		sort(nums.begin(), nums.end());
		for (int i = 0; i < nums.size(); ++i)
			ans.push_back(vector<int>(1, nums[i]));
		if (nums.size() != 1)
			ans.push_back(nums);
		for (int i = 2; i < nums.size(); ++i)
		{
			vector<int>tmp(i);
			cmb(0, 0, i, nums, tmp, ans);
		}
		ans.push_back(vector<int>());
		return ans;
	}
	void cmb(int pos,int deep, int& len, vector<int>& nums,vector<int>& t, vector <vector<int> >& ans)
	{
		if (deep == len)
		{
			ans.push_back(t);
			return;
		}
		for (int i = pos; i < nums.size(); ++i)
		{
			t[deep] = nums[i];
			cmb(i + 1, deep + 1, len, nums, t, ans);
		}
	}
};


内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:LeetCode-Subsets-解题报告
举报原因:
原因补充:

(最多只允许输入30个字)