[語法] 關於遞迴&合併字串

看板C_and_CPP (C/C++)作者 (人生遊戲 戲遊人生)時間15年前 (2010/08/15 18:13), 編輯推噓1(102)
留言3則, 2人參與, 最新討論串1/1
我找到一個列出所有排列的程式碼 其code如下: ------------------------------------------- #include <iostream> #include <stdlib.h> #include <string> using namespace std; void makesort(string p, string q); long total; int main() { string s; cout << "輸入要排列的文字《限半形字》:"; cin >> s; total = 0; makesort(s,""); cout << "共 " << total << " 組排列" << endl; system("pause"); return 0; } void makesort(string p, string q) { if(p == ""){ cout << q << endl; total++; } for(int i = 0; i < p.length(); i++) makesort(p.substr(0, i) + p.substr(i + 1, p.length() - 1 - i), q + p.substr(i, 1)); } -------------------------------------------------------------------------- 黃色的部份中 p.substr(0, i) + p.substr(i + 1, p.length() - 1 - i)不是等同於 p.substr(0, p.length() - 1 - i)嗎? 可是改成這樣跑出來結果是錯誤的 故意將一個字串拆成兩個字串相加 再代入遞迴 其意義何在? 還請各位大大不吝賜教 謝謝^^ -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 218.172.211.147

08/15 19:14, , 1F
每一層從 p 移除第 i 個元素給 q (i=0~n-1),往下遞迴
08/15 19:14, 1F

08/15 20:18, , 2F
阿 原來是我記錯用法了 substr後面的參數是長度才對!
08/15 20:18, 2F

08/15 20:19, , 3F
謝謝J大^^
08/15 20:19, 3F
文章代碼(AID): #1CPxt2tJ (C_and_CPP)
文章代碼(AID): #1CPxt2tJ (C_and_CPP)