回溯法 小象

#include 
#include 
using namespace std;
int main()
{
	vector nums;
	nums.push_back(1);
	nums.push_back(2);
	nums.push_back(3);
	vector item;
	vector > result;
	
	for(int i=0; i

 [1]
[1][2]
[1][2][3]

 

#include 
#include 
using namespace std;

void generate(int i,vector &nums , vector &item , vector > &result)
{
	if(i >= nums.size())
	{
		return;
	}
	item.push_back(nums[i]);
	result.push_back(item);
	generate(i+1 , nums , item , result);
}

int main()
{
	vector nums;
	nums.push_back(1);
	nums.push_back(2);
	nums.push_back(3);
	vector item;
	vector > result;
	
	generate(0 , nums , item , result);
	
	for(int i=0; i

[1]
[1][2]
[1][2][3]
 

方法1:

#include 
#include 
using namespace std;

class Solution {
public:
    vector > subsets(vector& nums) {
        vector > result;
        vector item;
        result.push_back(item);
        generate(0,nums,item,result);
        return result;
    }
private:
    void generate(int i,vector &nums , vector &item , vector > &result)
    {
        if(i>=nums.size())
        {
            return;
        }
        item.push_back(nums[i]);
        result.push_back(item);
        generate(i+1 , nums , item , result);
        item.pop_back();
        generate(i+1 , nums , item , result);
    }
};



int main()
{
	vector nums;
	nums.push_back(1);
	nums.push_back(2);
	nums.push_back(3);
	vector item;
	Solution solve; 
	vector > result;
	result = solve.subsets(nums);
	
//	generate(0 , nums , item , result);
	for(int i=0; i

[]
[1]
[1][2]
[1][2][3]
[1][3]
[2]
[2][3]
[3]
 

 方法二: 位运算

#include 
#include 
using namespace std;

class Solution {
public:
	vector > subsets(vector &nums)
	{
		vector > result;
		int all_set = 1<< nums.size();
		
		for(int i=0; i item;
			for(int j=0; j nums;
	nums.push_back(1);
	nums.push_back(2);
	nums.push_back(3);
	vector item;
	Solution solve; 
	vector > result;
	result = solve.subsets(nums);
	
//	generate(0 , nums , item , result);
	for(int i=0; i

[]
[1]
[2]
[1][2]
[3]
[1][3]
[2][3]
[1][2][3]
 

你可能感兴趣的:(算法,算法)