輸入乙個字串,按字典序列印出該字串中字元的所有排列。例如輸入字串abc,則列印出由字元a,b,c所能排列出來的所有字串abc,acb,bac,bca,cab和cba。
class
solution
void
permutation
(vector
&result,string str,
int start,
int end)
for(
int i=start;i
void
swap
(string &str,
int i,
int j)
};
可能自己對遞迴還是理解的不夠清晰;
**及更詳細解析第一次外層全部遞迴:
遞迴交換前:i:
0 start:
0 adc
遞迴交換後: i:
0 start:
0 adc--
----
----
----
----
->對應一次for迴圈結束時的str
遞迴交換前:i:
1 start:
1 adc --
-->第乙個內層迴圈
遞迴交換後: i:
1 start:
1 adc
遞迴交換前:i:
2 start:
2 adc --
-->最內層迴圈
遞迴交換後: i:
2 start:
2 adc --
->第乙個:push_back
遞迴後:i:
2 start:
2 adc
遞迴後:i:
1 start:
1 adc
遞迴交換前:i:
2 start:
1 adc --
>第二個內層迴圈 交換dc
遞迴交換後: i:
2 start:
1 acd
遞迴交換前:i:
2 start:
2 acd --
->最記憶體迴圈;
遞迴交換後: i:
2 start:
2 acd--
----
----
-->第二次
遞迴後:i:
2 start:
2 acd
遞迴後:i:
2 start:
1 acd --
->內層迴圈結束
遞迴後:i:
0 start:
0 adc --
-------
> 對應第一次迴圈交換後的結果
//第二層外層全部遞迴:
遞迴交換前:i:
1 start:
0 adc
遞迴交換後: i:
1 start:
0 dac--
----
----
----
>dac
遞迴交換前:i:
1 start:
1 dac
遞迴交換後: i:
1 start:
1 dac
遞迴交換前:i:
2 start:
2 dac
遞迴交換後: i:
2 start:
2 dac--
----
----
>第三次push_back
遞迴後:i:
2 start:
2 dac
遞迴後:i:
1 start:
1 dac
遞迴交換前:i:
2 start:
1 dac
遞迴交換後: i:
2 start:
1 dca
遞迴交換前:i:
2 start:
2 dca
遞迴交換後: i:
2 start:
2 dca--
----
----
->第四次
遞迴後:i:
2 start:
2 dca
遞迴後:i:
2 start:
1 dca
遞迴後:i:
1 start:
0 dac --
----
----
>dac
//第三層外層全部遞迴
遞迴交換前:i:
2 start:
0 dac
遞迴交換後: i:
2 start:
0 cad --
----
----
>cda
遞迴交換前:i:
1 start:
1 cad
遞迴交換後: i:
1 start:
1 cad
遞迴交換前:i:
2 start:
2 cad
遞迴交換後: i:
2 start:
2 cad--
-------
>第五次
遞迴後:i:
2 start:
2 cad
遞迴後:i:
1 start:
1 cad
遞迴交換前:i:
2 start:
1 cad
遞迴交換後: i:
2 start:
1 cda
遞迴交換前:i:
2 start:
2 cda
遞迴交換後: i:
2 start:
2 cda--
----
-->第6次;
遞迴後:i:
2 start:
2 cda
遞迴後:i:
2 start:
1 cda
遞迴後:i:
2 start:
0 cad --
----
>cda
遞迴過程**:和上面**思路有所不同;}//此處遇見a;結束
if(j ==0)
//從後往前找比第乙個下降值大且最小的元素位置
int k = str.
length()
-1;while
(k >= j)
else
}//交換上面找到的兩個字元的位置
char c = str[k]
; str[k]
= str[j -1]
; str[j -1]
= c;
//將後半部分遞減的字串,轉為遞增字串
swap_sort
(str, j, str.
length()
-1);
result.
push_back
(str);}
return result;
}void
swap_sort
(string &s,
int start,
int end)}}
;
9 字串排序
字串排序 time limit 1000 ms memory limit 65536 kb description 輸入3個字串,按字典序從小到大進行排序。input 輸入資料有一行,分別為3個字串,用空格分隔,每個字串長度不超過100。output 輸出排序後的三個字串,用空格分隔。sample ...
2133 字串排序
先輸入你要輸入的字串的個數。然後換行輸入該組字串。每個字串以回車結束,每個字串少於一百個字元。如果在輸入過程中輸入的乙個字串為 stop 也結束輸入。然後將這輸入的該組字串按每個字串的長度,由小到大排序,按排序結果輸出字串。字串的個數,以及該組字串。每個字串以 n 結束。如果輸入字串為 stop 也...
146 字串排序
題目描述 給定兩個字串 s1 和 s2,寫乙個函式來判斷 s2 是否包含 s1 的排列。換句話說,第乙個字串的排列之一是第二個字串的子串。示例1 輸入 s1 ab s2 eidbaooo 輸出 true 解釋 s2 包含 s1 的排列之一 ba 示例2 輸入 s1 ab s2 eidboaoo 輸出...