C++解决n连环问题(递归)

要求与规则

打印出所有步骤的算法

int16_t Baguenaudier(int16_t *memory, int16_t n) {
    int16_t move=0;
    Remove(memory, n,move);
    return move;//move is the number of steps
}

void Remove(int16_t *memory, int16_t n, int16_t &move) {
    if (!n) 
        return;
    else if(n==1){
        if(!move)
            memory[move] =1;
        else
            memory[move]=memory[move-1]+1;
        move++;
        return;
    }
    Remove(memory, n - 2,move);
    int16_t temp=1,i=0;
    for(i=1;i<n;i++)
        temp+=temp;
    if(!move)
        memory[move] =temp;
    else
        memory[move]=memory[move-1]+temp;
    move++;
    Put (memory, n - 2,move);
    Remove(memory, n - 1,move);
}

void Put(int16_t *memory, int16_t n, int16_t &move) {
    if (!n) 
        return;
    else if(n==1){
        memory[move]=memory[move-1]-1;
        move++;
        return;
    }
    Put (memory, n - 1,move);
    Remove(memory, n - 2,move);
    int16_t temp=1,i=0;
    for(i=1;i<n;i++)
        temp+=temp;
    memory[move]=memory[move-1]-temp;
    move++;
    Put(memory, n - 2,move);
}

仅求解下n连环的最少步骤数的算法

int fun(int n){
    if(n==0)
        return 0;
    else if(n==1)
        return 1;
    else
        return 2*fun(n-2)+fun(n-1)+1;
}

主函数

int main(){
    int n;
    cin>>n;
    cout<<"取下"<<n<<"个环所需最少次数为"<<fun(n)<<endl;
    int16_t memory[MAXLEN], move;
    move = Baguenaudier(memory, n);
    for(int j = 0; j < move; ++j)
        cout << bitset<16>(memory[j]) << endl;
}

相关推荐

  1. N/八皇后问题

    2024-02-02 23:32:03       60 阅读
  2. N 皇后问题解决方案 - 使用和回溯算法

    2024-02-02 23:32:03       46 阅读
  3. ——N皇后

    2024-02-02 23:32:03       38 阅读
  4. 实现 n^k

    2024-02-02 23:32:03       55 阅读
  5. 常见问题

    2024-02-02 23:32:03       31 阅读
  6. 解决问题的六种方法

    2024-02-02 23:32:03       67 阅读
  7. 解决链表问题中的应用

    2024-02-02 23:32:03       39 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-02-02 23:32:03       98 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-02-02 23:32:03       106 阅读
  3. 在Django里面运行非项目文件

    2024-02-02 23:32:03       87 阅读
  4. Python语言-面向对象

    2024-02-02 23:32:03       96 阅读

热门阅读

  1. Kubernetes实战(二十二)-Pod时区修改

    2024-02-02 23:32:03       58 阅读
  2. C# Newtonsoft.Json解析json笔记

    2024-02-02 23:32:03       46 阅读
  3. 【Git系列】修改远程分支名

    2024-02-02 23:32:03       58 阅读
  4. virtualBox虚拟机安装ubuntu后的必要配置

    2024-02-02 23:32:03       59 阅读
  5. 备考蓝桥杯每日一题——C++分支结构“ABC”

    2024-02-02 23:32:03       46 阅读
  6. 原子计数器缓冲区 Atomic Counter Buffers

    2024-02-02 23:32:03       43 阅读
  7. 蓝桥杯-景区导游-DFS

    2024-02-02 23:32:03       41 阅读
  8. 代码随想录算法训练营第二十四天|77. 组合

    2024-02-02 23:32:03       47 阅读
  9. 安卓之代码检查工具优劣分析以及应用场景

    2024-02-02 23:32:03       52 阅读
  10. 【Python】websockets库的介绍及用法

    2024-02-02 23:32:03       48 阅读