Thinking algorithms (recursive) Training: a string of M output sub-sequences

topic

From a string of length N in M ​​randomly selected characters (without breaking the original order) and output.

Thinking

This selection can be decomposed into:
1. Select the current character, and select the M-1 remaining characters
2. the current character is not selected, selection of M in the remaining characters
which have been substructure, consider outlet, when details of the output string, if the previously selected memory string, etc. can write code.

Code

/**
 * 输出长度为N的字符串的所有长度为M的子序列
 * */
public class RandomStrCharCombine {

  public static void main(String[] args) {
    String s = "ABCDE";
    M = 3;
    cache = new char[s.length()];
    select(s.toCharArray(), 0, M);
  }

  //存储选择的字符
  static char[] cache;
  //需要选取的字符的个数
  static int M;

  /**
   *
   * @param arr 字符数组
   * @param index 开始索引
   * @param num 选出字符数
   */
  private static void select(char[] arr, int index, int num) {
    //数量已经选够,输出cache
    if (num == 0) {
      System.out.println(String.valueOf(cache, 0, M));
      return;
    }
    if (index == arr.length) {
      return;
    }

    //不选索引处的字符,在剩余字符里面选择num个
    select(arr, index + 1, num);
    //取当前字符,并从剩余字符里面选num-1个
    cache[M - num] = arr[index];
    select(arr, index + 1, num - 1);
  }
}
Published 127 original articles · won praise 96 · views 310 000 +

Guess you like

Origin blog.csdn.net/zhengwei223/article/details/78766161