Home >Java >javaTutorial >Solution to combination arrangement problem in Java

Solution to combination arrangement problem in Java

高洛峰
高洛峰Original
2017-03-09 18:58:111431browse

This article introduces the solution to the combination arrangement problem in Java

1.

Select 2 people from 4 people to participate in the event. There are 6 selection methods in total.

How many ways are there to select m people from n people to participate in the event?

C(m/n)=C((m-1)/(n-1))+C(m/(n-1)) Mathematical algorithm


public class Main {	
	public static void main(String[] args) {
		System.out.println("请输入总人数:");
		Scanner sc=new Scanner(System.in);
		int n=sc.nextInt();
		System.out.println("请输入选择人数:");
		int m=sc.nextInt();
		System.out.println("一共有"+fun(n,m)+"种方法!");
	}	
	private static int fun(int n, int m) {		
		if(m>n)return 0;		
		if(m==0)return 1; 		
		return fun(n-1,m-1) + fun(n-1,m);
	}
}

2.

The problem of calculating how many arrangements of 3 A and 2 B can be formed (such as: AAABB, AABBA) is " The research field of Combinatorial Mathematics

. But in some cases, the fast computing speed of computers can also be used to solve problems through clever reasoning.

The following program calculates how many different arrangements m A's and n B's can be combined into. Please improve it.

A(n/m)=A(n/(m-1))+A((n-1)/m)


public class Main {
	public static void main(String[] args) {
		int m=3;
		int n=2;
		System.out.println(pailie(m, n));
	}
	public static int pailie(int m,int n){	
		if (m==0||n==0)return 1;	
		return pailie(m-1,n)+pailie(m, n-1); 
	}
}

Method 2

public class Main {
	public static void main(String[] args) {
		char[] date="ABC".toCharArray();
		f(date,0);
	}
	private static void f(char[] date, int k) {	
		if (k==date.length) {
			for (int i = 0; i < date.length; i++) {
				System.out.print(date[i]+" ");
			}
			System.out.println();
		}	
		for (int i = k; i < date.length; i++) {
			{char t=date[k];date[k]=date[i];date[i]=t;}//试探		
			f(date,k+1);		
			{char t=date[k];date[k]=date[i];date[i]=t;}//回溯
		}	
	}
}

The above is the detailed content of Solution to combination arrangement problem in Java. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn