Code for Variations with repetition (combinatorics)?

后端 未结 4 1570
伪装坚强ぢ
伪装坚强ぢ 2020-12-15 02:34

Does anyone have Java code for generating all VARIATIONS WITH REPETITION?

There are plenty of permutation and combination examples available, and variations must be

4条回答
  •  暖寄归人
    2020-12-15 03:20

    This works as is, and it's the easiest for you to study.

    public class Main {
        public static void main(String args[]) {
            brute("AB", 3, new StringBuffer());
        }
        static void brute(String input, int depth, StringBuffer output) {
            if (depth == 0) {
                System.out.println(output);
            } else {
                for (int i = 0; i < input.length(); i++) {
                    output.append(input.charAt(i));
                    brute(input, depth - 1, output);
                    output.deleteCharAt(output.length() - 1);
                }
            }
        }
    }
    

提交回复
热议问题