首页 新闻 搜索 专区 学院

求C#或JAVA实现A,B,C,D 4个字符串生成不同的排列

0
悬赏园豆:5 [已关闭问题] 关闭于 2016-10-17 10:02

A,B,C,D 4个字符生成不同的排列 (AB 和BA 当成是相同的字符串ABC侧不相同)

不语的主页 不语 | 初学一级 | 园豆:126
提问于:2014-12-06 15:51
< >
分享
所有回答(2)
0
static System.Collections.Specialized.StringCollection MakeStrings(string[] characters, int finalStringLength)
{
    int finalLength = finalStringLength; // The length of the final strings.
    System.Collections.Specialized.StringCollection existingStrings;
    System.Collections.Specialized.StringCollection newStrings =
        new System.Collections.Specialized.StringCollection(); // Start with the all one-letter combinations.

    newStrings.AddRange(characters);
    
    for (int len = 2; len <= finalLength; len++)
    {
        // Start a new collection of strings based on the existing strings.
        existingStrings = newStrings;
        newStrings = new System.Collections.Specialized.StringCollection();

        // Concatenate every string of length (len-1)...
        foreach (string str in existingStrings)
        {
            // ...with every character...
            foreach (string ch in characters)
            {
                // ...to create every possible string of length len.
                newStrings.Add(str + ch);
            }
        }
    }
    return newStrings;
}
没有名的用户 | 园豆:79 (初学一级) | 2014-12-06 17:07
0

你是想求不同的组合吗?我用java写的,你看看是不是你需要的(递归写的,所以效率低一点):

public class Test {
    public static void main(String[] args) {
        Test t = new Test();
        t.get("", 0);
    }
    
    private char [] chs = new char [] {'A', 'B', 'C', 'D'};
    
    public void get(String prev, int i) {
        if (i >= chs.length) {
            System.out.println(prev);
            return;
        }
        get(prev, i+1);
        get(prev + String.valueOf(chs[i]), i+1);
    }
}
琴剑飘零 | 园豆:409 (菜鸟二级) | 2014-12-07 05:24
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册