问题描述
河内塔问题: // { 驱动程序代码开始 // C++ 的初始模板
#include <bits/stdc++.h>
using namespace std;
// } Driver Code Ends
// User function Template for C++
class Solution{
public:
static int i=0;
void hanoi(vector<int>& v,int N,int n,int start,int end)
{
i++;
if(i==n)
{
v[0]=start;
v[1]=end;
return;
}
int other=6-(start+end);
hanoi(v,N-1,n,start,other);
hanoi(v,other,end);
}
vector<int> shiftPile(int N,int n){
// code here
Solution::i=0;
vector<int>v(2,0);
hanoi(v,N,1,3);
return v;
}
};
// { Driver Code Starts.
int main(){
int t;
cin>>t;
while(t--){
int N,n;
cin>>N>>n;
Solution ob;
vector<int> ans = ob.shiftPile(N,n);
cout<<ans[0]<<" "<<ans[1]<<endl;
}
return 0;
} // } Driver Code Ends
错误出现在类解决方案中,我无法声明它[C++禁止非常量静态成员解决方案::i的类内初始化]。请帮助解决上述问题。
解决方法
声明和定义静态数据成员如
class Solution{
public:
static int i;
//...
};
int Solution::i = 0;
虽然不清楚为什么使用存储类说明符 static 声明变量 i
。