簡體   English   中英

Java中的字符串排列(非遞歸)

[英]String permutations in Java (non-recursive)

我是一名10年級的高中生,試圖解決Java數據結構和算法書中的一些問題。

其中一個問題是打印字符串的所有排列。

class C14
{
public static void main(char a[])
{
    // char[] a = {'c','a','r','b','o','n'};
    int c=0,w=0;
    for(int q = 0;q<a.length;q++) 
    {
        for(int i=0;i<a.length;i++)
        {
            for(int j=1;j<a.length;j++)
            {
                for(int k=1;k<a.length-1;k++) 
                {
                    for(int z=0;z<a.length;z++)
                    {
                        System.out.print(a[z]);
                        c++;
                    }
                    w++;
                    System.out.println();
                    char p=a[k+1];
                    a[k+1]=a[k];
                    a[k]=p;
                }
                System.out.println();
            }
            System.out.println();
            char x=a[0];
            a[0]=a[1];
            a[1]=x;
        }
      }
    System.out.println(" Character count = " + c);
    System.out.println(" Word count = " + w);
    }
}

這是我的嘗試。 這本書要求我為人物'c','a','r','b','o','n'做這件事。 我的解決方案就是這樣,但當我嘗試使用3或4個字母的單詞時,它會讓我重復。 如果我刪除最外面的循環並嘗試打印它,它適用於3個和4個字母的單詞,但不適用於5個以上的單詞單詞。

我很樂意澄清我的理由,我知道這不是最有效的,但請記住我只是在10年級,這是我首先想到的。

有人可以幫幫我,或至少暗示什么是錯的? 請不要建議遞歸解決方案,因為我想先迭代地完成它。 謝謝,Sumit。

重復排列

當你有n個東西可供選擇時...你每次都有n個選擇!

當選擇r時,排列是:

n×n×...(r次)= n ^ r

我提出2個案例。 第一種情況是我們已經知道n和r的大小,而且很容易。 當n和r是動態的時候。

//when n and r are known statically

class Permutation
{
    public static void main(String[] args)
    {
        char[] values = {'a', 'b', 'c', 'd'};
        int n = values.length;
        int r = 2; 

        int i = 0, j = 0;
        for(i=0; i<n; i++)
        {
            for(j=0; j<n; j++)
            {
                System.out.println(values[j] + " " + values[i]);
            }
        }
    }
}


//when n and r are known only dynamically

class Permutation
{
    public static void main(String[] args)
    {
        char[] values = {'a', 'b', 'c', 'd'};
        int n = values.length;
        int r = 2; 
        int i[] = new int[r];
        int rc = 0;
        for(int j=0; j<Math.pow(n,r); j++)
        {

            rc=0;
            while(rc<r)
            {
                System.out.print(values[i[rc]] + " ");
                rc++;
            }
            System.out.println();
            rc = 0;
            while(rc<r)
            {
                if(i[rc]<n-1)
                {
                    i[rc]++;
                    break;
                }
                else
                {
                    i[rc]=0;
                }
                rc++;
            }
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM