【问题标题】:incrementing/decrementing n-bit binary by recursion (algorithm)通过递归(算法)递增/递减 n 位二进制
【发布时间】:2016-09-26 04:34:36
【问题描述】:

我有一个家庭作业问题,我们应该提出一个递归算法来查找从 0 开始的 n 位二进制数的七个排列(例如,如果 n=4,则起始数是 0000)。规则是对数字进行尽可能小的更改,一次仅更改 1 位,并获得尽可能小的十进制结果。

根据规则,第一个排列是 0001(十进制 1),第二个排列是 0011(十进制 3),第三个排列是 0010,依此类推。 我在问题中得到的排列如下:
1. 0000 = 0
2. 0001 = 1
3. 0011 = 3
4. 0010 = 2
5. 0110 = 6
6. 0100 = 4
7. 0101 = 5

我知道并理解递归是如何工作的,但我只能做简单的(数字序列、阶乘、排列等),我不知道如何提出递归算法,有人可以请吗帮忙?

【问题讨论】:

  • 你有没有尝试过?向我们展示你的方法。
  • @jbsu32 很抱歉,我真的没有任何想法:(

标签: algorithm recursion permutation


【解决方案1】:

如果你只想要 7 个最小的二进制字符串,我不确定你所说的“可能的最小十进制结果”是什么意思,因为你总是只有 0 - 110 但如果由于某种原因你不不想用C++mapping:

public class f {
    static int count = 0;
    static int n = 7;// n smallest binary strings

    /**
     * 
     * @param str initialize with ""
     * @param len number of bits
     */
    static void g(String str,int len){
        if(count<n) {
            if (len == 0) {
                count++;
                System.out.println(str);
            } else {
                g(str + "0", len - 1);
                g(str + "1", len - 1);
            }
        }
    }

    public static void main(String[] args) {
        g("",4);
    }
}

【讨论】:

    【解决方案2】:

    你可以试试这个方法->

    void rec(string s)
    {
        mapped[s]=true;                 /// Mapping the string, which will stop repetition
        cout<<s<<endl;                  /// Printing s
        for(int i=0; i<4; i++){         /// looping through s
            if(!mapped[toggle(s,i)]){   /// checking if toggled string is mapped
                rec(toggle(s,i));       /// Calling the toggled string
            }
        }
    }
    

    这里,s=0000toggle 切换字符串 si-th 位。这是给你的toggle函数->

    string toggle(string s, int pos){
        if(s[pos]=='1')s[pos]='0';
        else s[pos]='1';
        return s;
    }
    

    代码块输出这个 ->

    0000
    1000
    0000
    0100
    1100
    1110
    0110
    0010
    1010
    1011
    0011
    0111
    1111
    1101
    0101
    0001
    1001
    

    您可以在任何您希望的地方停止打印!!

    【讨论】:

    • 我还是有点迷茫,“映射”到底是做什么的?
    • 一个字符串是mapped,如果之前打印的话。
    • 我们如何知道它是否被更早地打印?对不起,我对此一无所知。
    • 你知道C++mapping吗???给你 -> cplusplus.com/reference/map/map/map
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-04-12
    • 2015-01-21
    • 1970-01-01
    • 2011-02-16
    • 2021-02-02
    • 2013-05-10
    相关资源
    最近更新 更多