二叉搜索树与双向链表、字符串的排列(剑指offer26-27)c++版本

#include 
#include 
#include 
#include 

using namespace std;

struct TreeNode {
	int val;
	struct TreeNode *left;
	struct TreeNode *right;
	TreeNode(int x) :
		val(x), left(NULL), right(NULL) {
	}
};

class Solution {
public:
	//JZ26 二叉搜索树与双向链表
	TreeNode* Convert(TreeNode* pRootOfTree);
	//JZ27 字符串的排列
	vector<string> Permutation(string str);
	vector<string> PermutationCore(string str, int len, int begin);
};
//JZ26
TreeNode* Solution::Convert(TreeNode* pRootOfTree) {
	if (!pRootOfTree)	return nullptr;
	if (!pRootOfTree->left && !pRootOfTree->right)
		return pRootOfTree;
	TreeNode* leftTable = Convert(pRootOfTree->left);
	if (leftTable) {
		TreeNode* leftNode = leftTable;
		while (leftNode->right) {
			leftNode = leftNode->right;
		}
		leftNode->right = pRootOfTree;
		pRootOfTree->left = leftNode;
	}
	TreeNode* rightTable = Convert(pRootOfTree->right);
	if (rightTable) {
		pRootOfTree->right = rightTable;
		rightTable->left = pRootOfTree;
	}
	return leftTable == nullptr ? pRootOfTree : leftTable;
}
//JZ27
vector<string> Solution::Permutation(string str) {
	//迭代求解。从左到右依次改变字符。
	if (str.empty())	return vector<string>();
	int len = str.size();
	vector<string> result = PermutationCore(str, len, 0);
	sort(result.begin(), result.end());
	return result;
}
vector<string> Solution::PermutationCore(string str, int len, int begin) {
	//从头到尾,每次固定一个位置
	vector<string> result;
	if (begin == len - 1)	result.push_back(str.substr(begin));
	if (begin > len - 1)	return vector<string>();	
	vector<string> temp = PermutationCore(str, len, begin+1);
	for (vector<string>::iterator it = temp.begin(); it != temp.end(); it++) {
		result.push_back(str[begin] + *it);
	}
	for (int i = begin + 1; i < len; i++) {
		if (str[i] != str[begin]) {
			char ch = str[i];
			str[i] = str[begin];
			str[begin] = ch;
			vector<string> temp = PermutationCore(str, len, begin + 1);
			for (vector<string>::iterator it = temp.begin(); it != temp.end(); it++) {
				result.push_back(str[begin] + *it);
			}
			ch = str[i];
			str[i] = str[begin];
			str[begin] = ch;
		}
	}
	return result;
}

//JZ26
void test1() {
	TreeNode* pHead = new TreeNode(5);
	pHead->left = new TreeNode(3);
	pHead->left->left = new TreeNode(1);
	pHead->left->right = new TreeNode(4);
	pHead->right = new TreeNode(8);
	Solution s;
	TreeNode* result = s.Convert(pHead);
	TreeNode* temp = result;
	while (temp) {
		cout << temp->val << ' ';
		temp = temp->right;
	}
	return;
}
//JZ27
void test2(){
	string str = "abc";
	Solution s;
	vector<string> result = s.Permutation(str);
	for (vector<string>::iterator it = result.begin(); it != result.end(); it++)
		cout << *it << endl;
	return;
}

int main() {
	//test1();
	test2();
	system("pause");
	return 0;
}

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