LeetCode(四)
- 打印一个字符穿的全部子序列:
-
package com.model.recursion; import org.omg.PortableServer.LIFESPAN_POLICY_ID; import java.util.ArrayList; import java.util.List; /** * @Description:测试类 * @Author: 张紫韩 * @Crete 2021/8/29 21:52 * 动态规划查找到一个字符串的所有子串 */ public class RecursionDemo01 { public static void main(String[] args) { String str="abc"; ArrayList<String> resList = new ArrayList<>(); getAllStr(str, 0, "",resList); for (String string:resList){ System.out.println(string); } } public static void getAllStr(String str,int index,String path,List<String> resList){ if (index==str.length()){ resList.add(path); return; } getAllStr(str, index+1, path+str.charAt(index),resList); getAllStr(str, index+1, path,resList); } }
-
-
打印出一个字符串的全排列:
-
package com.model.recursion; import java.util.ArrayList; import java.util.List; /** * @Description:测试类 * @Author: 张紫韩 * @Crete 2021/8/29 22:29 * 打印一个字符串的全排列 */ public class RecursionDemo02 { public static void main(String[] args) { char[] array="abc".toCharArray(); swap(array, 0, 2); // System.out.println(array); ArrayList<String> list = new ArrayList<>(); arrangement(array, 0,list); for (String str:list){ System.out.println(str); } } public static void arrangement(char[] array, int index, List<String> resList){ if (index==array.length){ resList.add(new String(array)); return; } for (int i = index; i <array.length; i++) { swap(array, index, i); arrangement(array, index+1,resList); swap(array, i,index); } } public static void swap(char[] array,int left,int right){ char l = array[left]; char r = array[right]; array[left]=r; array[right]=l; } }
-
package com.model.recursion; import java.util.ArrayList; import java.util.List; /** * @Description:测试类 * @Author: 张紫韩 * @Crete 2021/8/29 22:29 * 打印一个字符串的全排列,要求无重复的 */ public class RecursionDemo03 { public static void main(String[] args) { char[] array="abca".toCharArray(); // swap(array, 0, 2); //// System.out.println(array); ArrayList<String> list = new ArrayList<>(); arrangement(array, 0,list); for (String str:list){ System.out.println(str); } } public static void arrangement(char[] array, int index, List<String> resList){ if (index==array.length){ resList.add(new String(array)); return; } boolean[] arr = new boolean[26]; for (int i = index; i <array.length; i++) { if (!arr[array[i]-'a']) { arr[array[i]-'a']=true; swap(array, index, i); arrangement(array, index + 1, resList); swap(array, index, i); } } } public static void swap(char[] array,int left,int right){ char l = array[left]; char r = array[right]; array[left]=r; array[right]=l; } }
-
-