格式要遵照下面這兩行
void permute(const string &str);
void permute(const string &str, int low, int high); // 使用遞迴
第一個程序是一個驅動程式用來呼叫第二個程序並且在string str印出所有排列字元
例如如果str="abc",就要輸出 abcacb、bac、bca、cab、cba
此問題的 Base case 和 Design rule 我想好久...
但是因為這是初次碰到遞迴問題...
(教科書範例看的懂,但是自己寫寫不出來)
P.S.
附上原題目給大家參考:
The first routine is a driver that calls the second and prints all the permutations of the characters in string str.
If str is “abc”, then the strings that are output are abc, acb, bac, bca, cab, and cba.
Use 〝recursion〞 for the second routine.
名詞解釋
Base case:solve without recursion
Design rule:Assume that all the recursive calls work
/** Webcpp v0.7.0+ compatible StyleSheet http://webcpp.sf.net **/
/** Theme: ide-devcpp **/
body
{
background-color: #ffffff
}
a:link {color:#ff0000}
a:visited {color:#000080}
a:active {color:#000000}
a:hover {color:#008000}
pre
{
color: #000000
}
font
{
font-size:100%
}
font.preproc
{
color: #008000
}
font.numbers
{
color: #0000ff
}
font.strings
{
color: #ff0000
}
font.keyword
{
color: #000000;
font-weight: bold
}
font.comment
{
color: #000080;
font-style: italic
}
#include <iostream>
#include <string>
using std::string;
void permute(const string &);
void permute(const string &,int,int);
using std::cout;
int main()
{
string str("abc");
permute(str);
return 0;
}
void permute(const string &str)
{
permute(str,0,str.length());
}
void permute(const string &str,int low,int high)
{
string strx = str;
if (low == high -1)
cout << str << " ";
else {
for(int i=low;i < high ;++i) {
char temp = strx[i];
strx[i] = strx[low];
strx[low] = temp;
permute(strx,low+1,high);
strx[low] = strx[i];
strx[i] = temp;
}
}
}