劍指offer-字符串序列的全排列問題

/*******************************************************************
Copyright(c) 2016, Tyrone Li
All rights reserved.
*******************************************************************/
// 作者:TyroneLi
//

/*
Q:
    字符串的排列:
        輸入一個字符串,打印出該字符串的所有排列。
S:
    把一個字符串分成兩部扽,第一部分是第一個字符,然後是第二部分的剩下字符串;
    採用遞歸方法,剩下的字符串也這樣劃分;在每次劃分的時候把第一部分的第一個字
    符跟第二部分的所有字符串都交換。

*/

#include <iostream>
#include <cstdio>
#include <cstdlib>

void divide_permutation(char*str, char*begin)
{
    if((*begin) == '\0')
    {
        std::cout << str << std::endl;
    }

    for(char*ch = begin; (*ch) != '\0'; ++ch)
    {
        char tmp = *begin;
        *begin = *ch;
        *ch = tmp;

        divide_permutation(str, begin+1);

        tmp = *begin;
        *begin = *ch;
        *ch = tmp;
    }
}

void permutation(char*str)
{
    if(str == nullptr)
        return;
    
    divide_permutation(str, str);
}

void test_1()
{
    std::cout << "Test 1" << std::endl;
    char str[] = "abc";
    permutation(str);
    std::cout << std::endl;
}

void test_2()
{
    std::cout << "Test 2" << std::endl;
    char str[] = "a";
    permutation(str);
    std::cout << std::endl;
}

void test_3()
{
    std::cout << "Test 3" << std::endl;
    char str[] = "abcd";
    permutation(str);
    std::cout << std::endl;
}

void test_4()
{
    std::cout << "Test 4" << std::endl;
    char str[] = "";
    permutation(str);
    std::cout << std::endl;
}

void test_5()
{
    std::cout << "Test 5" << std::endl;
    char*str = nullptr;
    permutation(str);
    std::cout << std::endl;
}

void test_permutation()
{
    test_1();
    test_2();
    test_3();
    test_4();
    test_5();
}

int main(int argc, char**argv)
{

    test_permutation();

    return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章