取球问题
1 /* 2 * 取球问题: 3 * 从n个球中取出m个有多少种取法? 4 */ 5 6 public class Main { 7 8 public static void main(String[] args) { 9 System.out.println(quQiu(10, 3)); 10 } 11 12 static int quQiu(int n, int m) { 13 if (n < m) { 14 return 0; 15 } 16 if (n == m) { 17 return 1; 18 } 19 if (m == 0) { 20 return 1; 21 } 22 return quQiu(n - 1, m) + quQiu(n - 1, m - 1); // 弄一个特殊球,再分该球取不取两种情况 23 } 24 25 }
全排列问题
1 /* 2 * 全排列问题: 3 * 求n个元素的全排列? 4 */ 5 6 public class Main { 7 8 public static void main(String[] args) { 9 char[] a = "ABCDEFG".toCharArray(); 10 paiLie(a, 0); 11 } 12 13 static void paiLie(char[] a, int index) { 14 if (index == a.length) { 15 System.out.println(a); 16 } 17 for (int i = index; i < a.length; i++) { 18 char temp = a[index]; 19 a[index] = a[i]; 20 a[i] = temp; 21 22 paiLie(a, i + 1); 23 24 temp = a[index]; // 回溯 25 a[index] = a[i]; 26 a[i] = temp; 27 } 28 } 29 30 }
AB排列问题
1 /* 2 * 计算m个A,n个B可以组成多少排列? 3 * 如:AABB,ABB...... 4 */ 5 6 public class Main { 7 8 public static void main(String[] args) { 9 System.out.println(paiLie(2, 1)); 10 } 11 12 static int paiLie(int m,int n){ 13 if(m==0||n==0){ 14 return 1; 15 } 16 return paiLie(m-1, n)+paiLie(m, n-1); 17 } 18 19 }
最大子序列问题
/* * 最大子序列长度: * 求两个串的最大公共子序列长度? */ public class Main { public static void main(String[] args) { System.out.println(ziXuLieChangDu("abc", "xbacd")); } static int ziXuLieChangDu(String s1, String s2) { if (s1.length() <= 0 || s2.length() <= 0) { return 0; } if (s1.charAt(0) == s2.charAt(0)) { // 假设首位相等 return 1 + ziXuLieChangDu(s1.substring(1), s2.substring(1)); } else { return Math.max(ziXuLieChangDu(s1.substring(1), s2), ziXuLieChangDu(s1, s2.substring(1))); } } }
整数分化问题
1 /* 2 * 整数分化问题: 3 * 对于给定的正整数n,打印所有分化部分 4 */ 5 6 public class Main { 7 8 public static void main(String[] args) { 9 int[] a = new int[6]; 10 fenHua(6, a, 0); 11 } 12 13 static void fenHua(int n, int[] a, int index) { 14 if (n <= 0) { 15 for (int i = 0; i < index; i++) { 16 System.out.print(a[i] + " "); 17 } 18 System.out.println(); 19 } 20 for (int i = n; i > 0; i--) { 21 if (index > 0 && i > a[index - 1]) { //先大后小 22 continue; 23 } 24 a[index] = i; 25 fenHua(n - i, a, index + 1); 26 } 27 } 28 29 }
时间: 2024-10-01 02:48:48