• 生成全排列


    递归方法

    #include<iostream>
    using namespace std;
    
    void swap(int& a, int& b) {
    	int t = a;
    	a = b;
    	b = t;
    }
    void arrange(int *a, int n, int k) {
    	if (k > n) {
    		for (int i = 1; i <= n; i++) {
    			cout << a[i] << " ";
    		}
    		cout << endl;
    		return;
    	}
    	for (int i = k; i <= n; i++) {
    		swap(a[i], a[k]);
    		arrange(a, n, i+1);
    		swap(a[k], a[i]);
    	}
    }
    
    int main() {
    	int a[4] = { 0,1,2,3 };
    	arrange(a, 3, 1);
    	system("pause");
    }
    

    非递归

    void swap(int& a, int& b) {
    	int t = a;
    	a = b;
    	b = t;
    }
    
    bool next_permutation(int* a, int n) {
    	//从后往前找,找到第一个大于前面数字的数
    	int x = n;
    	while (x > 1) {
    		if (a[x] > a[x - 1]) {
    			x--;
    			break;
    		}
    		x--;
    	}
    
    	if (x == 1) return false; // 没有逆序,直接返回
    	int y;  //从后面找到一个大于a[x]并且是最小的数的下标
    	int min = INT_MAX;
    	for (int i = x + 1; i <= n; i++) {
    		if (a[i]< min && a[i]>a[x]) {
    			min = a[i];
    			y = i;
    		}
    	}
    	//交换两个数
    	swap(a[x], a[y]);
    	//调转逆序数字后的数组
    	for (int i = 1; x + i < n; i++) {
    		swap(a[x + i], a[n - i + 1]);
    	}
    	return true;
    }
    
    int main() {
    	int a[6] = { 0,1,2,3,4,5};
    	while (next_permutation(a, 5)) {
    		for (int i = 1; i <= 5; i++) {
    			cout << a[i] << " ";
    		}
    		cout << endl;
    	}
    	system("pause");
    }
    
  • 相关阅读:
    Java-对象数组排序
    aoj 0118 Property Distribution
    poj 3009 Curling 2.0
    poj 1979 Red and Black
    AtCoder Regular Contest E
    AtCoder Beginner Contest 102
    AtCoder Beginner Contest 104
    SoundHound Inc. Programming Contest 2018
    poj 3233 Matrix Power Series
    poj 3734 Blocks
  • 原文地址:https://www.cnblogs.com/urahyou/p/13719461.html
Copyright © 2020-2023  润新知