C#:0&;1排列

C#:0&;1排列,c#,permutation,combinations,C#,Permutation,Combinations,我想列出只有0和1的排列。与二进制相似,但允许可变长度,不必等于8长度。例如: 0 1 00 01 10 11 000 001 010 011 100 101 110 111 一直到X的长度满足为止。如何做到这一点?我会将其作为递归调用,一个函数用于执行所有特定长度,另一个函数用于调用所有相关长度。下面完整的C#2008控制台应用程序说明了我的意思: using System; namespace ConsoleApplication1 { class Program {

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

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

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

我会将其作为递归调用,一个函数用于执行所有特定长度,另一个函数用于调用所有相关长度。下面完整的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);
        }
    }
}

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

我会将其作为递归调用,一个函数用于执行所有特定长度,另一个函数用于调用所有相关长度。下面完整的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);
        }
    }
}
这就是我认为您所追求的。

您也可以使用:

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'));
            }
        }
    }
}
使用系统;
课堂测试
{
静态空隙置换(内部长度)
{
对于(int i=1;i,您还可以使用:

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'));
            }
        }
    }
}
使用系统;
课堂测试
{
静态空隙置换(内部长度)
{

因为(int i=1;我看了看啊,我脑子里到底是怎么想的,但没有正确地表达出来。)这太神奇了。你到底是怎么想出这样一个解决方案的?我向你鞠躬,例外!啊,我脑子里到底是怎么想的,但没有正确地表达出来的。:)这太神奇了。你到底是怎么想出这样一个解决方案的?我向你鞠躬,例外!