递归和动态规划-汉诺塔II

来源:互联网 发布:矩阵开关介绍 编辑:程序博客网 时间:2024/06/05 04:39

题目描述:

        有一个int数组arr其中只含有1、2和3,分别代表所有圆盘目前的状态,1代表左柱,2代表中柱,3代表右柱,arr[i]的值代表第i+1个圆盘的位置。比如,arr=[3,3,2,1],代表第1个圆盘在右柱上、第2个圆盘在右柱上、第3个圆盘在中柱上、第4个圆盘在左柱上。如果arr代表的状态是最优移动轨迹过程中出现的状态,返回arr这种状态是最优移动轨迹中的第几个状态。如果arr代表的状态不是最优移动轨迹过程中出现的状态,则返回-1。
给定一个int数组arr及数组的大小n,含义如题所述,请返回一个int,代表所求的结果。
测试样例:
[3,3]
返回:3

递归版本的AC代码:

class Hanoi {public:    int process(vector<int> &arr,int i,int from,int mid,int to){        if(i==-1)            return 0;        if(arr[i]!=from && arr[i]!=to)            return -1;        if(arr[i]==from)            return process(arr,i-1,from,to,mid);        else{            int res=process(arr,i-1,mid,from,to);            if(res==-1)                return -1;            return (1<<i)+res;        }    }    int chkStep(vector<int> arr, int n) {        // write code here        if(arr.empty()||n<=0)            return -1;        return process(arr,n-1,1,2,3);    }};
非递归版本的AC代码:

class Hanoi {public:    int chkStep(vector<int> arr, int n) {        // write code here        if(arr.empty()||n<=0)            return -1;        int from=1,mid=2,to=3;        int rest=0,tmp=0;        while(n>=1){            if(arr[n-1]!=from && arr[n-1]!=to)                return -1;            if(arr[n-1]==to){                rest+=1<<(n-1);                tmp=from;                from=mid;            }            else{                tmp=to;                to=mid;            }            mid=tmp;            n--;        }        return rest;    }};



0 0
原创粉丝点击