题目:给定一个有重复字符的字符串,求其全排列
import java.util.*;
class Main1 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);//输入一个字符串
String str = scan.nextLine();//字符串赋给str
permutation(str.toCharArray(), 0,str.length()-1);//调用permutation方法
}
public static void permutation(char[] str, int start,int end) {
if (start > end || str == null) {//边界值判断
return;
}
if (start == end) {//递归到最后一位时打印出字符数组
System.out.print(String.valueOf(str) + " ");//将数组转换成字符串输出
} else {
for (int i = start; i <= end; i++) {//遍历数组
if (isSwap(str, start, i)) {//判断是否重复
char temp = str[start];
str[start] = str[i];
str[i] = temp;
permutation(str, start + 1,end);
temp = str[start];
str[start] = str[i];
str[i] = temp;
}
}
}
}
public static boolean isSwap(char[] str, int start, int i) {//定义方法,str[i]在之前是否出现过
for (int k = start; k < i; k++) {
if (str[k] == str[i]) {
return false;
}
}
return true;
}
}
输出:
aasd
aasd aads asad asda adsa adas saad sada sdaa dasa daas dsaa
上面的是一种重复字符串的全排列,如果是不重复字符串的全排列,去掉isSwap()方法即可
全组合:
public class AllCombination {
public static void main(String[] args) {
int[] nums = {1,2,3};
subsets(nums);
}
public static List<List<Integer>> subsets(int[] nums) {
List<List<Integer>> lll = new ArrayList<>();
int n = nums.length;
int pn = 1<<n;
for (int i = 0;i< pn;i++){
System.out.print("输出第"+i+"个是:");
ArrayList<Integer> ll = new ArrayList<>();
for (int j = 0; j < n; j++) {
int temp = 1<<j;
if ((temp & i) != 0){
ll.add(nums[j]);
}
}
System.out.println(ll);
lll.add(ll);
}
return lll;
}
}
输出第0个是:[]
输出第1个是:[1]
输出第2个是:[2]
输出第3个是:[1, 2]
输出第4个是:[3]
输出第5个是:[1, 3]
输出第6个是:[2, 3]
输出第7个是:[1, 2, 3]