Java string redirects given by integer

I am trying to perform permutations in java of a string given by an integer.

So, if String is "abc" and Integer Number is 2.

I need the following results:

ab ac bc bc california CB

If the string is also "abc" but the integer is 3, I want to get the following results:

a bac ba bca taxi ACB

I already have the following method:

private static void permutation(String prefix, String str) {
        int n = str.length();
        if (n == 0) permutationsList.add(prefix);
        else {
            for (int i = 0; i < n; i++)
                permutation(prefix + str.charAt(i), str.substring(0, i) + str.substring(i+1, n));
        }
    }

But this only works for an Integer equal to the size of the string, in this case 3.

So can something help me do this work with an Integer argument?

Thanks in advance;)

0
source share
2 answers

DFS, .

:

import java.util.ArrayList;
import java.util.List;

/**
 * @author mifmif
 * 
 */
public class DFS {

    /**
     * list of generated combination
     */
    List<String> permutations = new ArrayList<String>();
    /**
     * input used to generate combination
     */
    String input = "ABCDEF";
    /**
     * the length of the combination
     */
    int conbinationSize = 3;
    /**
     * isChoosed[i] is true if the combination that is currently prepared
     * contain index.charAt(i)
     */
    boolean[] isChoosed = new boolean[input.length()];

    /**
     * the DFS method that will generate all possible combination
     * 
     * @param partialOutput
     */
    public void generateCombination(String partialOutput) {
        if (partialOutput.length() == conbinationSize) {
            permutations.add(partialOutput);
            return;
        }
        for (int i = 0; i < input.length(); ++i) {
            if (!isChoosed[i]) {
                isChoosed[i] = true;
                generateCombination(partialOutput + input.charAt(i));
                isChoosed[i] = false;
            }
        }

    }

    void printCombination() {
        for (String c : permutations) {
            System.out.println(c);
        }
    }

    public static void main(String[] args) {
        DFS dfs = new DFS();
        dfs.generateCombination("");
        dfs.printCombination();
    }
}
+1

IDE/ , .

, k ? , k ? 'ABC', , 'A', 'BC' 'A'. , , 'ABC', 'B' 'C'?

, , , k .

:

perms(string, k)
    if length(string) == 0 or k == 0
         // do what?
    else
       for every character in string
           for every sub-permutation in perms(*some modified string*, *some modified k-value*)
                // the permutation is character + sub-permutation
0

All Articles