字符串的排列

xiaoxiao2021-02-28  145

题目:输入一个字符串,打印出该字符串中字符的所有排列。 例:输入字符串 abc        输出:abc acb bac bca cab cba 思路:把一个字符串分为两部分,第一部分为其第一个字符,第二部分为后面所有字符。然后把第一个字符逐一和它后面的字符交换。递归思路。 #include<iostream> using namespace std; #include<assert.h> void Permutation(char* pStr, char* pBegin) { assert(pStr && pBegin); if (*pBegin == '\0') printf("%s\n", pStr); else { for (char* pCh = pBegin; *pCh != '\0'; pCh++) { swap(*pBegin, *pCh); Permutation(pStr, pBegin + 1); swap(*pBegin, *pCh); } } } int main(void) { char str[] = "abc"; Permutation(str, str); return 0; }
转载请注明原文地址: https://www.6miu.com/read-29692.html

最新回复(0)