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 122. Best Time to Buy and Sell Stock II 股票买卖2 解题报告

1 解题思想首先请看下第一个问题: Leetcode 121. Best Time to Buy and Sell Stock 股票买卖 解题报告 题目给定的数组还是一样的含义,依旧代表股票的价...

leetcode解题报告15. 3Sum

leetcode解题报告15. 3Sum题目地址 难度是medium题目描述输入一个整数数组,从中选择3个数,使得这三个数之和为0,这三个数称为一个三元组。现在要求所有满足要求的三元组。并且要求三元组...

[leetcode] 138. Copy List with Random Pointer 解题报告

题目链接:https://leetcode.com/problems/copy-list-with-random-pointer/ A linked list is given such that...

[LeetCode] 419. Battleships in a Board 解题报告

Given an 2D board, count how many battleships are in it. The battleships are represented with 'X's, ...

【LeetCode】Substring with Concatenation of All Words 解题报告

【题目】 You are given a string, S, and a list of words, L, that are all of the same length. Find all ...

【LeetCode】Trapping Rain Water解题报告

【题目】 Given n non-negative integers representing an elevation map where the width of each bar is...

LeetCode 513. Find Bottom Left Tree Value 解题报告

LeetCode 513. Find Bottom Left Tree Value 解题报告题目描述Given a binary tree, find the leftmost value in th...

LeetCode-The Skyline Problem-解题报告

LeetCode-The Skyline Problem-解题报告

【LeetCode】Remove Duplicates from Sorted Array 解题报告

【LeetCode】Remove Duplicates from Sorted Array 解题报告标签(空格分隔): LeetCode[LeetCode]https://leetcode.com/p...

Leetcode 125. Valid Palindrome 回文验证 解题报告

1 解题思想就一个简单的判断一个string里面的字符和数字部分,是否是回文的,不考虑符号和大小写等其实说白了,就首尾指针对比一下就好。。 我代码里面首尾不同的地方时过滤下非字符数字2 原题Given...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

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