C++递归实现全排列

来源:互联网 发布:淘宝开店店名 编辑:程序博客网 时间:2024/06/18 14:57

本文采用递归算法实现数组元素全排列

// filename: perm-recur.cpp#include <iostream>using namespace std;template <class T>// swap a and binline 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 permutationfor (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-recurOBJ = perm-recur.o$(APP_NAME): $(OBJ)g++ $^ -o $(APP_NAME)%.o:%.cppg++ $(CFLAGS) -c $^ -o $@# remove object files and executable when user executes "make clean"clean:rm *.o $(APP_NAME)


0 0