leetcode #78 in cpp

原创 2016年06月02日 09:07:39

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


  • 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:


As long as we know how to find combination of certain length( in #77), this question would be very easy. Simply loop for every possible length, and in each loop we find all combinations of this length. 


class Solution {
    vector<vector<int>> subsets(vector<int>& nums) {
        vector<vector<int>> res; 
        sort(nums.begin(), nums.end());//sort to avoid duplicates
        res.push_back(vector<int>());//empty set 
        //find the combinations of length need starting from num[i]
        for(int need = 1;need <= nums.size(); need ++){//for each length 
            for(int i = 0; i < nums.size(); i ++)//start from each position to find combination
                find_subsets(i, need - 1, vector<int>(),nums, res);
        return res;
    void find_subsets(int start_ind, int need, vector<int> member,vector<int> &nums, vector<vector<int>> &res){
        //need does not include num[start_ind]
        if(need > nums.size() - 1 - start_ind) return;//if need > num between [start .....num.size() - 1], we could not do it. //Say need = 4 and the num[start position + 1....end] = [2,3] this could only provide 2 numbers < 4. We could terminate it 
        if(need == 0){
        for(int i = start_ind + 1; i < nums.size(); i ++)
            find_subsets(i, need - 1, member, nums, res);


leetcode #114 in cpp

Given a binary tree, flatten it to a linked list in-place. For example, Given 1 ...

leetcode #160 in cpp

Write a program to find the node at which the intersection of two singly linked lists begins. F...

Leetcode 285. Inorder Successor in BST (Medium) (cpp)

Leetcode 285. Inorder Successor in BST (Medium) (cpp)
  • Niko_Ke
  • Niko_Ke
  • 2016年12月28日 03:38
  • 240

leetcode #139 in cpp

Given a string s and a dictionary of words dict, determine if s can be segmented into a space-separa...

leetcode #86 in cpp

Given a linked list and a value x, partition it such that all nodes less than x come before nodes gr...

leetcode #149 in cpp

Given n points on a 2D plane, find the maximum number of points that lie on the same straight line...

leetcode #24 in cpp

The question is to swap each pair in the linked list. And the requirement is to use constant space. ...

Leetcode 450. Delete Node in a BST (Medium) (cpp)

Leetcode 450. Delete Node in a BST (Medium) (cpp)
  • Niko_Ke
  • Niko_Ke
  • 2016年12月26日 07:50
  • 269

leetcode #36 in cpp.

The question is to determine a Sudoku is valid.  Solution:  if a Sudoku is valid, each row, each co...

*leetcode 138 in cpp

A linked list is given such that each node contains an additional random pointer which could point t...
您举报文章:leetcode #78 in cpp