【问题标题】:C#: 0 & 1 PermutationsC#:0 和 1 排列
【发布时间】:2010-08-09 03:46:14
【问题描述】:

我想列出只有 0 和 1 的排列。类似于二进制但允许可变长度,不必等于 8 长度。例如:

0
1
00
01
10
11
000
001
010
011
100
101
110
111

一直到满足 X 的长度。如何做到这一点?

【问题讨论】:

标签: c# permutation combinations


【解决方案1】:

你也可以使用:

using System;

class Test
{
    static void permute(int len)
    {
        for (int i=1; i<=len; i++) 
        {
            for (int j=0; j<Math.Pow(2, i); j++)
            {
                Console.WriteLine (Convert.ToString(j, 2).PadLeft(i, '0'));
            }
        }
    }
}

不涉及递归:)

【讨论】:

  • 啊,和我想象的完全一样,但没有正确传达。 :)
  • 这太棒了。你到底是怎么想出这样的解决方案的?我向你鞠躬,NullUserException!
【解决方案2】:

我会将此作为递归调用,一个函数执行所有特定长度,另一个函数调用所有相关长度。以下完整的 C# 2008 控制台应用程序说明了我的意思:

using System;

namespace ConsoleApplication1 {
    class Program {
        static void permuteN(string prefix, int len) {
            if (len == 0) {
                System.Console.WriteLine(prefix);
                return;
            }
            permuteN(prefix + "0", len - 1);
            permuteN(prefix + "1", len - 1);
        }

        static void permute(int len) {
            for (int i = 1; i <= len; i++)
                permuteN("", i);
        }

        static void Main(string[] args) {
            permute(3);
        }
    }
}

这个输出:

0
1
00
01
10
11
000
001
010
011
100
101
110
111

这就是我认为你所追求的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-06-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-20
    • 1970-01-01
    相关资源
    最近更新 更多