蛙跳

題目9:一隻青蛙一次可以跳上一級臺階,也可以跳上兩級。求該青蛙跳上一個n級臺階總共有多少種情況。


#include <iostream>
using namespace std;
//N 代表目標數字
#define N 10

class Solution
{
private:
	int * mNumArray = new int[N + 1];
	int mSteps[2];
	int mArrayIndex = 0;
public:
	Solution()
	{
		memset(mNumArray, 0 , sizeof(int)*(N + 1));
		mSteps[0] = 1;
		mSteps[1] = 2;
	}
	//回溯法
	void Jump(int steps)
	{
		if (steps == N)
		{
			Print();
			return;
		}
		else if (steps > N)
			return;

		for (int i = 0; i < 2; ++i)
		{
			mNumArray[mArrayIndex++] = mSteps[i];
			Jump(steps + mSteps[i]);
			mNumArray[--mArrayIndex] = 0;
		}
		
	}

	void Print()
	{
		for (int i = 0; i < mArrayIndex; ++i)
		{
			cout <<mNumArray[i] << " ";
		}
		cout <<"\n\n"<< endl;
	}

	~Solution()
	{
		delete[] mNumArray;
	}

};

int main()
{
	Solution solution;
	solution.Jump(0);
	return 0;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章