排列问题的其中一种解法

来源:互联网 发布:mac eclipse 调试 编辑:程序博客网 时间:2024/06/06 08:27


实现代码:

#include<iostream>using namespace std;const int maxNumber = 5;void Perm(int list[], int direct[], int number){int num = number;int index = -1;while (num > 0){//寻找num的下标for (int i = 0; i < number; i++){if (list[i] == num){index = i;break;}}//判断num是否的活动数if (direct[num - 1] == 0 && index == 0){num--;}else if (direct[num - 1] == 0 && index > 0){if (list[index] > list[index - 1]){int temp = list[index];list[index] = list[index - 1];list[index - 1] = temp;for (int i = 0; i < number; i++){cout << list[i] << " ";}cout << endl;//改变所有比num要大的数的方向for (int i = num; i < number; i++){direct[i] = direct[i] ^ 1;}//重置numnum = number;}else{num--;}}else if (direct[num - 1] == 1 && index == number - 1){num--;}else if (direct[num - 1] == 1 && index < number - 1){if (list[index] > list[index + 1]){int temp = list[index];list[index] = list[index + 1];list[index + 1] = temp;for (int i = 0; i < number; i++){cout << list[i] << " ";}cout << endl;//改变所有比num要大的数的方向for (int i = num; i < number; i++){direct[i] = direct[i] ^ 1;}//重置numnum = number;}else{num--;}}}}int main(void){int list[maxNumber];int direct[maxNumber];for (int j = 0; j < maxNumber; j++){list[j] = j + 1;//direct对于的是每个数的方向,0为向左,1为向右direct[j] = 0;}for (int i = 0; i < maxNumber; i++){cout << list[i] << " ";}cout << endl;Perm(list, direct, maxNumber);return 0;}



0 0
原创粉丝点击