# 回溯法求全排列和所有子序列

// ConsoleApplication6.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <vector>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
int count1 = 0;
int count2 = 0;
int count3 = 0;

int number = 0;
class Solution {
public:

vector<vector<int> > subsets(vector<int> &S) {
vector<vector<int> > ret;
if (S.size() == 0) return ret;
//sort(S.begin(), S.end());
vector<int> tmp;
dfs(S, 0, tmp, ret);
return ret;
}

void dfs1(vector <int> S, int begin, int end, vector <vector<int>> &ret)
{
count2++;
if (begin == end)
{
count1++;
ret.push_back(S);
//return;
}
else
{
//int k = S[0];
for (int i = begin;i < end; i++)
{
count3++;
swap(S[i], S[begin]);
dfs1(S, begin + 1,end, ret);
swap(S[begin], S[i]);

}
}
}

/*
void dfs(vector <int> &S, int begin, vector<int> tmp, vector <vector<int>> &ret)
{
ret.push_back(tmp);
if (begin >= S.size()) return;
for (int i = 0;i < S.size();i++)
{
tmp.push_back(S[i]);
dfs(S, i + 1, tmp, ret);
tmp.pop_back();
}
}
*/
void dfs(vector<int> &S, int beg, vector<int> tmp, vector<vector<int> > &ret) {
number++;
ret.push_back(tmp);
if (beg >= S.size()) return;
for (int i = beg; i < S.size(); ++i) {
tmp.push_back(S[i]);
dfs(S, i + 1, tmp, ret);
tmp.pop_back();
}
}

};

void main()
{
vector <int> m = {1,2,3,4};
Solution sol;
vector <vector <int>> vec;
vector <vector <int>> vec1;
//vector <vector <int>> vec =  sol.subsets(m);

sol.dfs1(m, 0, 4,vec);
vec1 = sol.subsets(m);
system("pause");

}

11-15 770

01-27 2964
07-17 1万+
05-21 1万+
06-03 5246
03-17 2398
03-02 2588
08-28 6258
09-27 9314
06-16 1382
01-06 505
03-22 1562
08-03 2969
03-29 806
05-25 1308