zoukankan      html  css  js  c++  java
  • 九度OJ 1120 全排列 -- 实现C++STL中next_permutation()

    题目地址:http://ac.jobdu.com/problem.php?pid=1120

    题目描述:

    给定一个由不同的小写字母组成的字符串,输出这个字符串的所有全排列。
    我们假设对于小写字母有'a' < 'b' < ... < 'y' < 'z',而且给定的字符串中的字母已经按照从小到大的顺序排列。

    输入:

    输入只有一行,是一个由不同的小写字母组成的字符串,已知字符串的长度在1到6之间。

    输出:

    输出这个字符串的所有排列方式,每行一个排列。要求字母序比较小的排列在前面。字母序如下定义:
    已知S = s1s2...sk , T = t1t2...tk,则S < T 等价于,存在p (1 <= p <= k),使得
    s1 = t1, s2 = t2, ..., sp - 1 = tp - 1, sp < tp成立。

    样例输入:
    abc
    样例输出:
    abc
    acb
    bac
    bca
    cab
    cba
    提示:

    每组样例输出结束后要再输出一个回车。

    来源:
    2008年北京大学图形实验室计算机研究生机试真题

    图片来自参考资料


    #include <stdio.h>
    #include <string.h>
    
    void Swap(char str[], int i, int j);
    void Reverse(char str[], int first, int last);
    int next_permutation(char str[], int first, int last);
    
    int main(void)
    {
    	int len;
    	char str[10];
    	while (scanf("%s", str) != EOF){
    		len = strlen(str);
    		printf("%s
    ", str);
    		while (next_permutation(str, 0, len)){
    			printf("%s
    ", str);
    		}
    		printf("
    ");
    	}
    	
    	return 0;
    }
    
    int next_permutation(char str[], int first, int last){
    	int i, j;
    	i = last - 2;
    	while (i >= 0 && str[i] >= str[i+1])
    		--i;
    	if (i == -1){
    		Reverse(str, first, last);
    		return 0;
    	}
    	j = last - 1;
    	while (str[j] <= str[i]){
    		--j;
    	}
    	Swap(str, i, j);
    	Reverse(str, i + 1, last);
    	return 1;
    }
    
    void Swap(char str[], int i, int j){
    	char temp;
    	temp = str[i];
    	str[i] = str[j];
    	str[j] = temp;
    }
    
    void Reverse(char str[], int first, int last){
    	last--;
    	while (first < last){
    		Swap(str, first++, last--);
    	}
    }

    九度OJ上相似的题目:http://ac.jobdu.com/problem.php?pid=1369

    LeetCode上相似的题目:http://oj.leetcode.com/problems/next-permutation/

    参考资料:ACM Cheat Sheet


  • 相关阅读:
    Yii2 composer报错处理
    bootstrap元素居中
    前端面试题
    control-lable的用法
    jenkins持续集成搭建
    gitlab管理平台搭建
    mysql8.0.11安装
    nexus私服搭建、配置、使用
    mysql5.7.22安装
    nginx配置阿里云免费ssl证书实现https化
  • 原文地址:https://www.cnblogs.com/liushaobo/p/4373755.html
Copyright © 2011-2022 走看看