左神算法基础class8—题目1求n!
1.求n!
(1)题目:求n!的结果
(2)分析
两种思路:正向和逆向
①正向思考n!就是从1开始不断累乘到n
long getFactorial1(int n)
{
int res = 1;
for(int i = 1; i <= n; ++i)
{
res *= i;
}
return res;
}
②逆向思考:n! = n * (n - 1)!
而 (n - 1)! = (n - 1) *(n - 2)!
,不断递归,停止条件是当n == 1
时,n!= 1
long getFactorial2(int n)
{
if(n == 1)
return 1;
return n * getFactorial2(n - 1);
}
2.汉诺塔问题
(1)题目:打印n层汉诺塔从最左边移动到最右边的全部过程
(2)分析
抽象整个过程,from为原位置,to是目的位置,help是辅助位置
①把1 ~ n-1 的数从from移动到help
②把最后一个数n放到to位置
③最后把1 ~ n-1 的数从help移动到to
#include<iostream>
#include<string>
using namespace std;
//N 表示目前是1-N的问题,切都在from上
void Hanoi(int N ,string from, string to,string help)
{
if(N == 1) //只剩一个数直接移动到to位置
cout<<" move 1 from " << from << " to "<< to<<endl;
else
{
//先把 n - 1 个数from到help,这时辅助组为to
Hanoi(N - 1,from,help,to);
//把最后一个数n放到to位置
cout<<" move " << N <<" from " << from << " to "<< to<<endl;
//把1 ~ n - 1 的数从help移动到to,这时辅助组为from
Hanoi(N - 1,help,to,from);
}
}
int main()
{
Hanoi(5,"左","右","中");
return 0;
}
(3)复杂度分析
①把1 ~ n-1 的数从from移动到help : T(n - 1)
②把最后一个数n放到to位置 : 1
③最后把1 ~ n-1 的数从help移动到to : T(n - 1)
实际是等比数列, 一共2^ n - 1 步,O(2^ n )