C++递归实现全排列
2016-05-20 16:43
357 查看
本文采用递归算法实现数组元素全排列
// filename: perm-recur.cpp
#include <iostream>
using namespace std;
template <class T>
// swap a and b
inline void permSwap(T &a, T &b)
{
T temp = a;
a = b;
b = temp;
}
template <class T>
// generate all permutation of list[k : m]
static void perm(T list[], int k, int m)
{
int i = 0;
static int count = 0;
if (k == m)
{
count++;
cout << "No." << count << " : ";
// print one permutation
for (i = 0; i <= m; i++)
{
cout << list[i];
}
cout << endl;
}
else
{
for (i = k; i <= m; i++)
{
permSwap(list[k], list[i]);
perm(list, k + 1, m);
permSwap(list[k], list[i]);
}
}
}
int main()
{
char list[] = {'a', 'b', 'c', 'd'};
int n = 0;
n = sizeof(list)/sizeof(list[0]);
perm(list, 0, n - 1);
return 0;
}
Makefile
# build perm-recur executable when user executes "make"
APP_NAME = perm-recur
OBJ = perm-recur.o
$(APP_NAME): $(OBJ)
g++ $^ -o $(APP_NAME)
%.o:%.cpp
g++ $(CFLAGS) -c $^ -o $@
# remove object files and executable when user executes "make clean"
clean:
rm *.o $(APP_NAME)
// filename: perm-recur.cpp
#include <iostream>
using namespace std;
template <class T>
// swap a and b
inline void permSwap(T &a, T &b)
{
T temp = a;
a = b;
b = temp;
}
template <class T>
// generate all permutation of list[k : m]
static void perm(T list[], int k, int m)
{
int i = 0;
static int count = 0;
if (k == m)
{
count++;
cout << "No." << count << " : ";
// print one permutation
for (i = 0; i <= m; i++)
{
cout << list[i];
}
cout << endl;
}
else
{
for (i = k; i <= m; i++)
{
permSwap(list[k], list[i]);
perm(list, k + 1, m);
permSwap(list[k], list[i]);
}
}
}
int main()
{
char list[] = {'a', 'b', 'c', 'd'};
int n = 0;
n = sizeof(list)/sizeof(list[0]);
perm(list, 0, n - 1);
return 0;
}
Makefile
# build perm-recur executable when user executes "make"
APP_NAME = perm-recur
OBJ = perm-recur.o
$(APP_NAME): $(OBJ)
g++ $^ -o $(APP_NAME)
%.o:%.cpp
g++ $(CFLAGS) -c $^ -o $@
# remove object files and executable when user executes "make clean"
clean:
rm *.o $(APP_NAME)
相关文章推荐
- [转]c++ 中__declspec 的用法
- UML 之 C++类图关系全面剖析
- 多态(C++版)
- C++ 之 声明与定义的区别
- 斐波那契数列
- 一种实现C++反射功能的想法(一)
- C++引用作为函数参数
- c++ curl下载和上传数据——c++(学习一)
- C++ std::bind思考
- <<Effective C++>>读书笔记1: 让自己习惯C++
- C++著名类库
- L1-010. 比较大小(C++)
- 简化版 栈的C++实现及栈的函数模板
- c++学习之运算符重载
- PAT (Basic Level) Practise (中文)1052. 卖个萌 (20)
- 关于C++ vector<S>使用时,错误 5 error C2719: “_Val”: 具有 __declspec(align('16')) 的形参将不被对齐
- 计蒜客之整除问题
- win32程序使用C++/CX语法
- C++ inline函数和template函数
- c++ primer plus 第13章习题