赞
踩
Cmn
- public class Main {
- static int M = 5;
- static int N= 3;
- static int[] a= new int[]{1,2,3,4,5};
- static int[] b = new int[N];
-
- public static void main(String[] args){
- C(M,N);
- }
-
- static void C(int m,int n){
- int i,j;
- for(i=n;i<=m;i++) {
- b[n-1] = i-1;
- if(n>1)
- C(i-1,n-1);
- else {
- for(j=0;j<=N-1;j++)
- System.out.print(a[b[j]] + " ");
- System.out.println();
- }
- }
- }
- }
Amn
- public class Main {
- static int M = 5;
- static int N = 3;
- static int[] a = new int[]{1, 2, 3, 4, 5};
- static int[] b = new int[N];
-
- public static void main(String[] args) {
- P(M, N);
- }
-
- static void P(int m, int n) {
- if (n == 0) {
- // 输出当前排列
- for (int i = 0; i < N; i++) {
- System.out.print(a[b[i]] + " ");
- }
- System.out.println();
- return;
- }
-
- // 从 m 中选出一个数放入排列中
- for (int i = 0; i < m; i++) {
- boolean used = false;
- for (int j = 0; j < N - n; j++) {
- if (b[j] == i) {
- used = true;
- break;
- }
- }
- if (!used) {
- b[N - n] = i;
- // 递归调用,选出下一个数
- P(m, n - 1);
- }
- }
- }
- }
求子集
- public void generateSubsets(String s, String subset, int index) {
- if (index == s.length()) {
- System.out.println(subset); // 输出当前子集
- return;
- }
- generateSubsets(s, subset + s.charAt(index), index + 1); // 包含当前字符
- generateSubsets(s, subset, index + 1); // 不包含当前字符
- }
-
- String str = "abc";
- generateSubsets(str, "", 0); // 调用函数生成所有子集
- public class Main {
- public static void main(String[] args) {
- int[] arr = {1, 2, 3, 4};
- f(arr, 0);
- }
-
- public static void f(int[] arr, int k) {
- if (k == arr.length) {
- // 打印当前排列
- for (int num : arr) {
- System.out.print(num + " ");
- }
- System.out.println();
- } else {
- for (int i = k; i < arr.length; i++) {
- // 交换位置
- int temp = arr[i];
- arr[i] = arr[k];
- arr[k] = temp;
-
- // 递归调用
- f(arr, k + 1);
-
- // 恢复交换前的状态,以便下一次迭代
- temp = arr[i];
- arr[i] = arr[k];
- arr[k] = temp;
- }
- }
- }
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。