1. 程式人生 > >演算法導論 第二章 遞迴與分治

演算法導論 第二章 遞迴與分治

階乘函式  斐波那契數列

#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;

// 階乘函式
int fact(int n)
{
    if(!n) return 1;
    return n * fact(n-1);
}

// 斐波那契數列
int fib(int n)
{
    if(n <= 1) return 1;
    return fib(n-1)+fib(n-2
); } int main() { cout << "fact(5) "<<fact(5) <<endl; cout << "fib(5) "<<fib(5) <<endl; return 0; }
階乘 斐波那契

 

排列問題

#include <iostream>
#include <cstring>
#include <algorithm>
#include <math.h>
using
namespace std; // 陣列長度 排列總數 int n, ans; /** *@param s 陣列首地址 *@param k 已經匹配完成[0,k-1] *@param n 陣列總長度 */ void Perm(int *s,int k, int n) { if(k >= n) { for(int i=0; i<=n; i++) { cout<< s[i] <<" "; } cout<< endl; ans
++; return ; } for(int i=k; i<=n; i++) { swap(s[k], s[i]); Perm(s, k+1, n); swap(s[k], s[i]); } } int main() { // 輸入陣列長度 並輸入相應數量的數 cin >> n; int *s = new int[n]; for(int i=0;i<n;i++) { cin >> s[i]; } // 對輸入的數 進行排序 sort(s, s+n); cout <<endl; Perm(s, 0, n-1); cout << "排列總數 " << ans<<endl; return 0; }
排列問題 對以後的排列樹有前置作用