Recursive full array and the DFS (depth search implementation)

Depth-first search implementation:

public class DFS {
	public static int [] arr = {1,2,3,4,5,6,7,8,9};
	public static int [] visited = {0,0,0,0,0,0,0,0,0};
	public static char [] ch =new char[9];
	static void dfs1(int n){//数字的全排列 伪全排列
		if(n==9){
			System.out.println(Arrays.toString(arr));
			}
		for(int i=0;i<=9;i++){//所有卡片的值
			if(visited[i]==0){//卡片没有用过
				visited[i]=1;//设置用过了
				arr[n]=i;
				dfs1(n+1);
				visited[i]=0;
			}
		}
		}
	static void dfs2(int n){//字符串的全排列 伪全排列
		if(n==9){
			String str = new String(ch);
			System.out.println(str);
		}
		for(char i='a';i<='i';i++){
			if(visited[i-97]==0){
				visited[i-97]=1;
				ch[n]=i;
				dfs2(n+1);
				visited[i-97]=0;
			}
		}
	}
	}

Recursive: the exchange of ideas! ! !

The main idea:
each character and the characters following it can be exchanged (and can own exchange)
such as a character string abc exchange - get -> abc, bac, cba.
The second character is then exchanged
an ABC-> abc, ACB
BAC-> BAC, BCA
CBA-> the CBA, CAB
get full array of strings
to big problems into small problems, exactly in line with the idea of recursion

public class 字符串的递归全排列 {

	public static void  DFS(char[]str,int i){//i是交换的字符位置
		if(i==str.length){//交换到最后一个了 进行输出
			System.out.println(new String(str));
		}
		for(int j=i;j<=str.length-1;j++){//每一个字符可以跟后面的字符进行交换
			swap(str,i,j);//把第i个字符和第j个进行交换
			DFS(str,i+1);//交换i+1个字符
			swap(str,i,j);//换回来
		}
	}
	
	static void swap(char[] str, int i, int j) {
		char a = str[i];
		str[i] = str[j];
		str[j] = a;
	}
	public static void main(String[] args) {
		Scanner in = new Scanner(System.in);
		String str = in.next();
		DFS(str.toCharArray(),0);
	}
	}

Guess you like

Origin blog.csdn.net/weixin_43752167/article/details/91358418