给定一个字符串,求出该字符串的所有组合(假设无重复字符)
str=“abc”,那么其组合有[a,b,c,ab,ac,bc,abc]
思路:
以abc为例,它的组合的结果为 2的3次方-1,即7种。那么枚举1——7,则每个值的二进制可代表一种情况:
1: 001 str[2] -----> c
2: 010 str[1] -----> b
3: 011 str[1]+str[2] -----> bc
4: 100 str[0] -----> a
5: 101 str[0]+str[2] -----> ac
6: 110 str[0]+str[1] -----> ab
7: 111 str[0]+str[1]+str[2] -----> abc
代码实现:
private static List<String> combine(String str){
List<String> re=new ArrayList<>();
int len=str.length();
int allConditions=(int)Math.pow(2,len)-1;
for (int i = 1; i <= allConditions; i++) {
String binary=Integer.toBinaryString(i);
// 上面得到的二进制不一定就是len长度的,前面的0被省略掉了
// 因为当二进制串的位置j如果为1的话,会去str中取出对应str[j]作为结果
// 所以这里需要记录差值
int div=len-binary.length();
StringBuilder temp=new StringBuilder();
for(int j=binary.length()-1;j>-1;j--){
if (binary.charAt(j)=='1'){
temp.append(str.charAt(div+j));
}
}
re.add(temp.toString());
}
return re;
}
补充:
去重的话,直接用set,没想到其它好的办法。
参考:
https://www.cnblogs.com/boris1221/p/9388209.html
类似问题:
leetcode:77. 组合
输入: n = 4, k = 2
输出:
[
[2,4],
[3,4],
[2,3],
[1,2],
[1,3],
[1,4],
]
基于回溯算法,注意过程中的剪枝。
public List<List<Integer>> combine(int n, int k) {
List<List<Integer>> re=new ArrayList<>();
if(n<1 || k<1){
return re;
}
combineConcrete(n,k,re);
return re;
}
static LinkedList<Integer> stack=new LinkedList<>();
public void combineConcrete(int n, int k,List<List<Integer>> re) {
// k==0表示得到一组解
if (k==0){
re.add(new ArrayList<>(stack));
return;
}
// 剪枝:n<=0了,肯定没法在放了。n<k这里思路是,现在需要还需要k个数,但是剩余的能够组合的数的个数n,已经小于了k
if (n<=0 || n<k){
return;
}
// 组合包含第n个数的情况
stack.push(n);
// 剩余的子问题为:在剩下n-1个数中选择k-1数,组成k个数的组合
combineConcrete(n-1,k-1,re);
// 组合不包含第n个数的情况
// 先把上面放进去的第n个数弹出
stack.pop();
// 剩余子问题为,在剩下n-1个数中选择k个数,组成k个数的组合
combineConcrete(n-1,k,re);
}