演算法思維(遞迴)訓練:輸出字串長度為M的子序列
阿新 • • 發佈:2019-01-25
題目
從長度為N的字串中隨機選出M個字元(不打破原有順序)並輸出。
思路
此選擇問題可分解為:
1. 選擇當前字元,並在剩餘字元中選擇M-1個
2. 不選擇當前字元,在剩餘字元中選擇M個
這就得到了子結構,再考慮出口、何時輸出字串、如果儲存之前選擇的字串等細節問題就能寫出程式碼。
程式碼
/**
* 輸出長度為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);
}
}