您的位置:首页 > 编程语言 > C语言/C++

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)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: