微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何创建递归算法来查找给定两个字母的排列?

如何解决如何创建递归算法来查找给定两个字母的排列?

我正在尝试创建一个递归程序来生成重复字母 X 和 O 的排列,例如,如果我想要 XO 的排列,它将给出: XO,OX,XX,OO 或者,如果我想要 XOX 的排列,它会给出: XXX,OOO,XOO,XXO,OXX,OOX,XOX,OXO

到目前为止,我有这个:

    public class driver {

    public static void main(String[] args) {
        permutation("XO");
    }
    
        public static void permutation(String input){ 
            permutation("",input); 
        }
        
        private static void permutation(String perm,String word) {
            if (word.isEmpty()) {
                System.err.println(perm + word);

            } else {
                for (int i = 0; i < word.length(); i++) {
                    permutation(perm + word.charat(i),word.substring(0,i) 
                                            + word.substring(i + 1,word.length()));
                }
            }
    }

}

然而,XO 的输出只会给出 XO 和 OX。我将如何修改我上面给出的例子?

这是最终目标,一旦我弄清楚如何正确生成排列,因为我首先要找到排列,将每个单独的 perm 添加到它们自己的数组中(将使用二维数组),并使用该数组生成最后的话。我将用找到的每个排列数组替换每个隐藏元素,以便创建完整的单词:

This is the end goal,as I am first going to find permutations,add them to an array,and use the array to generate final words.

解决方法

您可以使用以下代码获得递归排列。

public class driver { 
  
    // Function to print all the permutations of str 
    static void printPermutn(String str,String ans) 
    { 
  
        // If string is empty 
        if (str.length() == 0) { 
            System.out.print(ans + " "); 
            return; 
        } 
  
        for (int i = 0; i < str.length(); i++) { 
  
            // ith character of str 
            char ch = str.charAt(i); 
  
            // Rest of the string after excluding  
            // the ith character 
            String ros = str.substring(0,i) +  
                         str.substring(i + 1); 
  
            // Recurvise call 
            printPermutn(ros,ans + ch); 
        } 
    } 
  
    // Driver code 
    public static void main(String[] args) 
    { 
        String s = "XOX"; 
        printPermutn(s,""); 
    } 
} 

它将输出以下内容:XOX XXO OXX OXX XXO XOX

链接:https://ideone.com/ClZYk4

,

您可以根据您的要求使用以下代码。


import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Scanner;
import java.util.Set;
import java.util.TreeSet;

public class Sample2 {
    // static set that stores all combinations
    public static Set<String> combinations = new TreeSet<String>();

    public static void main(String[] args) {

        // Create an alphabet to work with
        String s = "XOX";
        char[] alphabet = s.toCharArray();
        // Find all possible combinations of this alphabet in the string size of 3
        possibleStrings(s.length(),alphabet,"");
        combinations.forEach(l -> {
            System.out.println(l);
        });
    }

    public static void possibleStrings(int maxLength,char[] alphabet,String curr) {

        // If the current string has reached it's maximum length
        if (curr.length() == maxLength) {
//              System.out.println(curr);
            combinations.add(curr);

            // Else add each letter from the alphabet to new strings and process these new
            // strings again
        } else {
            for (int i = 0; i < alphabet.length; i++) {
                String oldCurr = curr;
                curr += alphabet[i];
                possibleStrings(maxLength,curr);
                curr = oldCurr;
            }
        }
    }
//  }
}


输出为

OOO
OOX
OXO
OXX
XOO
XOX
XXO
XXX

这适用于任何给定的字符串。

,

使用递归:

static public void printPermutation(String word) {

    char[] chars = word.toCharArray();

    char[] state = new char[chars.length];

    Arrays.fill(state,' ');
    helper(chars,state,0);

}

static public void helper(
    char[] chars,char[] state,int index
) {

    if (index == chars.length) {
        System.out.println(new String(state));
        return;
    }

    for (int i = 0; i < chars.length; i++) {

        if (state[i] == ' ') {
            state[i] = chars[index];
            helper(chars,index + 1);
            state[i] = ' ';
        }

    }
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。