首页 > 其他 > 详细

LeetCode_45permute [Permutations]

时间:2014-07-21 23:27:40      阅读:447      评论:0      收藏:0      [点我收藏+]
#pragma warning(disable:4996)

#include <cstdio>
#include <tchar.h>
#include <Windows.h>
#include <vector>
using namespace std;

/*
	submit time : 1
	request :
		Given a collection of numbers, return all possible permutations.

		For example,
		[1,2,3] have the following permutations:
		[1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], and [3,2,1].
*/

void Swap(int* data, int i, int j) {
	int temp = data[i];
	data[i] = data[j];
	data[j] = temp;
}

void helpPermute(vector<vector<int> >& result, vector<int>& num, int length, int index) {
	if (index == length - 1)
		result.push_back(num);

	int vernier = index;
	while (vernier < length) {
		Swap(&num[0], index, vernier);
		helpPermute(result, num, length, index + 1);
		Swap(&num[0], index, vernier);
		++vernier;
	}
}

vector<vector<int> > permute(vector<int> &num) {
	vector<vector<int> > result;
	int length = num.size();
	if (length == 0) return result;

	helpPermute(result, num, length, 0);

	return result;
}

//===================Test====================
void printVec(vector<int>& vec) {
	vector<int>::iterator iter = vec.begin();
	for (; iter != vec.end(); ++iter)
		printf("%d ", *iter);
	printf("\n");
}

void Test(vector<int>& num) {
	vector<vector<int> > result = permute(num);
	vector<vector<int> >::iterator iter = result.begin();
	for (; iter != result.end(); ++iter)
		printVec(*iter);

	printf("\n");
}

void Test1() {
	int data[] = { 3, 7, 9, 13 };
	vector<int> num(data, data + sizeof(data) / sizeof(int));
	Test(num);
}

int _tmain(int arc, _TCHAR* argv[]) {
	Test1();

	system("pause");
	return 0;
}



LeetCode_45permute [Permutations],布布扣,bubuko.com

LeetCode_45permute [Permutations]

原文:http://my.oschina.net/ITHaozi/blog/293568

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!