C#:0& 1排列 [英] C#: 0 & 1 Permutations

查看:145
本文介绍了C#:0& 1排列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想列出仅包含0和1的排列.类似于二进制,但允许可变长度,不必等于8个长度.例如:

I want to list permutations with only 0 and 1. Similar to binary but allowing variable lengths, doesn't have to equal 8 length. For example:

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

一直到满足X的长度为止.该怎么办?

All the way until the length of X is met. How can this be done?

推荐答案

我将其作为递归调用进行,一个函数可以处理所有特定的长度,另一个函数可以对所有相关的长度进行调用.以下完整的C#2008控制台应用程序说明了我的意思:

I would do this as a recursive call, one function to do all of a specific length, another to call that for all relevant lengths. The following complete C# 2008 console application shows what I mean:

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

这就是我想你想要的.

这篇关于C#:0&amp; 1排列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆