• 递归详解


    递归详解

    在计算机科学领域, 递归是用于处理一类具有相同子问题处理方式的问题;
    是数学归纳法, 数学递推公式在计算机中的应用

    The power of recursion evidently lies in the possibility of defining an infinite set of objects by a finite statement. In the same manner, an infinite number of computations can be described by a finite recursive program, even if this program contains no explicit repetitions.
    --- by Niklaus Wirth, Algorithms + Data Structures = Programs, 1976

    用递归的方法来解决问题的关键, 在于准确找到子问题

    递归的简单应用

    1. 阶乘

    计算 \(n! = n *(n-1)* \dots *2* 1\)

    即令 \(f(n) = n * f(n-1)\)

    void Recursion_Factorial(int n)
    {
        if(n == 1) return n;
        return n * Recursion_Factorial(n-1);
    }
    

    2. 寻找所有子集

    template<class T>
    void Recursion_Subset(vector<T> dataSet, vector<vector<T>>& result)
    {
    	if (dataSet.empty()) { result.push_back({}); }
    	else
    	{
    		T data = dataSet.back();
    		dataSet.pop_back();
    		Recursion_Subset(dataSet, result);
    		int size = result.size();
    		for (int i = 0; i < size; i++)
    		{
    			result.push_back(result[i]);
    			result.back().push_back(data);
    		}
    	}
    	return;
    }
    
  • 相关阅读:
    正则表达式学习1
    SELECT INTO 和 INSERT INTO SELECT 两种表复制语句
    (转)DBUS基础知识
    WakeLock的使用
    观察者模式
    Notification的使用
    Head First 设计模式之入门
    (转)Android WebView总结
    书架也是一根筋
    PendingIntent分析
  • 原文地址:https://www.cnblogs.com/InfField/p/16642715.html
Copyright © 2020-2023  润新知