跳到正文

个人记录

daf

___QnQ___约 3 分钟
原文
文章信息与版本

文章信息

发布
2026年2月22日
收录
2026年3月22日
更新
2026年11月15日
篇幅
约 3 分钟

版本

  1. v2当前
  2. v1

%==================================% %====By ___QnQ___ (uid 2072014)====% %==================================% \gdef \var#1{\textit{#1}} \gdef \longvar#1{\textmd{\textrm{#1}}} \gdef \const#1{\texttt{#1}} \gdef \O#1{\mathcal{{O}}\!\left(#1\right)} \gdef \success{#52C41A} \gdef \error{#E74C3C} \gdef \warning{#FFC116} \gdef \info{#3498DB} \gdef \sign{{\color{#34AFCE}\underline{\textcolor{#3498DD}{\texttt{>>}}}}\;} \gdef\pink{ffc1d6} \gdef\lightpink{fee9fa} \gdef\purple{5e72e4} \gdef\lightpurple{efeffc} \gdef\blue{4f8be2} \gdef\lightblue{e9f1fb} \gdef\cyan{00b8d4} \gdef\lightcyan{e5f8fb} \gdef\green{19af7a} \gdef\lightgreen{d5f9ec} \gdef\yellow{eae918} \gdef\lightyellow{feffdd} \gdef\orange{fe9186} \gdef\lightorange{ffded6} \gdef\red{fe7280} \gdef\lightred{fee1e9} \gdef\white{ffffff} \gdef\lightwhite{f5f6fa} \gdef\gray{dfe6e9} \gdef\darkgray{2d3436} %==================================% %====By ___QnQ___ (uid 2072014)====% %==================================%

::anti-ai[由 ___QnQ___ 撰写,侵权必究。]

代码
C++
template <template<typename> typename T>
void all_comb(int n, int pos, T& path) {
    if (pos == n) {
        for (int num : path) cout << num << " ";
        cout << "\n";
        return;
    }

    for (int i = 1; i <= n; ++i) {
        path[pos] = i;
        all_comb(n, pos + 1, path);
    }
}
分析

这个函数每进入一次 for 就会递归 n\var{n} 次,然后又进入 for ……总共的循环次数为 O ⁣(nn)\O{\var{n}^\var{n}} 次。

这个的时间复杂度为 O ⁣(nn)\O{\var{n}^\var{n}},而且会Segmentation fault\color{\error}\const{Segmentation fault}(递归栈溢出)。

>>‾  \sign 所以请不要使用这种算法了。

STL\textcolor{\blue}{\textsf{STL}}才是正解。

原文