一個函式在執行過程中呼叫自己
A. 終止條件 (Base Case)
當問題縮小到最簡單、可以直接得到答案 的情況時,直接回傳結果。
B. 遞迴步驟 (Recursive Step)
將「大問題」轉化為「小問題」的過程
用遞迴來定義
一般定義
int factorial(int n) {
if (n == 1) { // 終止條件
return 1;
}
return n * factorial(n-1); // 遞迴步驟
}費式數列定義
int f(int n) {
if (n == 1 || n == 2) { // 終止條件
return 1;
}
return f(n - 1) + f(n - 2); // 遞迴步驟
}把1, 2, 3三個數字隨意排列,總共有哪些組合
1 2 3
1 3 2
2 1 3
2 3 1
3 1 2
3 2 1
把1, 2, 3三個數字隨意排列,總共有哪些組合
void permutations(int n, vector<int> v, vector<int> used)
{
if(v.size() == n)
{
for(auto i : v)
cout << i <<" ";
cout <<"\n";
return;
}
for(int i = 1; i <= n; i++)
{
if(used[i])
continue;
v.push_back(i);
used[i] = 1;
permutations(n, v, used);
v.pop_back();
used[i] = 0;
}
}