有一个字符串,根据输入参数m,找出字符串的m个字符的所有字符串
String str ="abc", m=2 得到结果是 "ab" "ac" "bc"
String str ="abcd" , m=3 得到结果是"abc" "acd" "bcd" "abd"
code:
/**
* 分治思想
*
* @param target
* @param num
* @return
*/
public static List<String> choose(String target, int num) {
List<String> resultList = new LinkedList<>();
if (num > target.length()) {
return resultList;
}
if (num == target.length()) {
resultList.add(target);
return resultList;
}
// 将target均分(0 ~ bound - 1与bound ~ end)
int bound = target.length() / 2;
String left = target.substring(0, bound);
String right = target.substring(bound, target.length());
// 要选择的num个元素可能全部来自left
resultList.addAll(choose(left, num));
// 可能全部来自right
resultList.addAll(choose(right, num));
// 可能两边都有,这时对num做划分:num = l + r(l表示来自left的元素的个数,r表示来自right的元素的个数)
for (int l = 1; l < num; l++) {
int r = num - l;
// 从left中挑选l个元素
List<String> fromLeftList = choose(left, l);
// 从right中挑选r个元素
List<String> fromRightList = choose(right, r);
// 组合起来
for (String fromLeft : fromLeftList) {
for (String fromRight : fromRightList) {
// 添加到结果集里面
resultList.add(fromLeft + fromRight);
}
}
}
return resultList;
}
|
|