c++ 按位异或计算进行状态的存储
在有的题目中需要对状态进行记录,使用数组记录状态占用的内存空间过多,可以使用int类型的数二进制据进行记录,在判断时对每一位进行异或就好。具体操作如下:
<<为左移操作。
相关题目:464
bool dfs(int state,int sum,int maxChoosableInteger,int desiredTotal){
if(vis[state]==1) return true;
if(vis[state]==2) return false;
for(int x=1;x<=maxChoosableInteger;x++){
if((1<<(x-1))&state) continue;//已被选过
if(sum+x>=desiredTotal){
vis[state]=1;
return true;
}
if(!dfs((1<<(x-1))|state,sum+x,maxChoosableInteger,desiredTotal)){
vis[state]=1;
return true;
}
}
vis[state]=2;
return false;
}