Foundations of Fortune left class8- subject seeking 1,2 n! , Tower of Hanoi problem

1. seek n!

(1) Title:! N seeking results

(2) analysis

Two ideas: forward and reverse
① positive thinking n! 1 is from the beginning constantly tired to take n

long getFactorial1(int n)
{
	int res = 1; 
	for(int i = 1; i <= n; ++i)
	{
		res *= i;
	}
	return res;
}

② reverse thinking: n! = n * (n - 1)!while (n - 1)! = (n - 1) *(n - 2)!constantly recursive, stop that when n == 1the time,n!= 1

long getFactorial2(int n)
{
	if(n == 1)
		return 1;
	return n * getFactorial2(n - 1);
}

2. Tower of Hanoi problem

(1) Title: n-layer printed HANOR moved from the left to the right-most the entire process

(2) analysis

Abstract The whole process, from the original position, to a destination location, help is an auxiliary position
Here Insert Picture Description
① to the number of 1 ~ n-1 from moving from the Help
② the number n place to a final position
③ finally 1 ~ n-1 to move from number to help

#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) Complexity Analysis

① The number of 1 ~ n-1 from moving from to help: T (n -. 1)
② the number n place to a final position:. 1
③ Finally, the number of 1 ~ n-1 from moving to help to: T (n - 1)
Here Insert Picture Description
is actually a geometric sequence, a total of 2 ^ n - 1 steps, O (2 ^ n)

Published 51 original articles · won praise 1 · views 1364

Guess you like

Origin blog.csdn.net/shi_xiao_xuan/article/details/104819472