如何将单词呈现的所有情况连接成一个句子 JAVA

How to concatenate all cases of word presentation in a sentence JAVA

输入: n 个单词的列表“word1 word2 word3...wordn

输出: 所有排列表示案例串联的字符串列表为:

s1: "word1 word2"
s2: "word1 word3"
s3: "word2 word1"
s4: "word2 word3"
s5: "word3 word1"
s6: "word3 word1"
s7: "word1 word2 word3"
s8: "word1 word3 word2"
s9: "word2 word1 word3"
s10: "word2 word3 word1"
s11: "word3 word1 word2"
s12: "word3 word2 word1"
...
sm: "wordn...word3 word 2 word 1"

我试试这个代码:

    public static List<String> PermuteWords(String s){
        String[] ss = s.split(" ");
        boolean[] used = new boolean[ss.length];
        String res = "";
        List<String> list = new ArrayList<String>();
        permute(ss, used, res, 0, list);
        return list;
    }

    private static void permute(String[] ss, boolean[] used, 
        String res, int level, List<String> list) {

        if (level == ss.length && res != ""){
            list.add(res);
            return;
        }

        for (int i = 0; i < ss.length; i++) {
            if (used[i]) {
                continue;
            }
            used[i] = true;
            permute(ss, used, res + " " + ss[i], level + 1, list);
            used[i] = false;
        }
    }

    public static void main(String args[]){

        String inputString="word1 word2 word3";
        List<String> test=PermuteWords(inputString);

        for (int i = 0; i < test.size(); i++) {
            System.out.println(test.get(i));
        }
    }

输出:

 word1 word2 word3
 word1 word3 word2
 word2 word1 word3
 word2 word3 word1
 word3 word1 word2
 word3 word2 word1

但是它缺少一些案例:

s1: "word1 word2"
s2: "word1 word3"
s3: "word2 word1"
s4: "word2 word3"
s5: "word3 word1"
s6: "word3 word1"

有谁能解决这个问题吗?

这样的怎么样?

private static void permute(String[] ss, boolean[] used,
                            String res, int level, List<String> list) {

    // End case
    if (level == ss.length && res != ""){
        list.add(res);
        return;
    }

    for (int i = 0; i < ss.length; i++) {
        // Check if the string is currently used
        if (used[i]) {
            continue;
        }
        // Check if res is empty or a single word
        if(level > 1)
            list.add(res);
        used[i] = true;
        permute(ss, used, res + " " + ss[i], level + 1, list);
        used[i] = false;
    }
}

输出:

 word1 word2
 word1 word2 word3
 word1 word3
 word1 word3 word2
 word2 word1
 word2 word1 word3
 word2 word3
 word2 word3 word1
 word3 word1
 word3 word1 word2
 word3 word2
 word3 word2 word1

我认为代码的问题是只有当递归结束时才将元素添加到列表中,不允许像你想要的那样添加子元素。