排列組合(百度百科)
排列組合是組合學最基本的概念。所謂排列,就是指從給定個數的元素中取出指定個數的元素進行排序。組合則是指從給定個數的元素僅僅取出指定個數的元素,不考慮排序。排列組合的中心問題是研究給定要求的排列和組合可能出現的情況總數。排列組合與古典概率論關係密切。
舉例說明
//abc的排列
abc acb bac bca cba cab
共有6種排序
//abc的組合
3取3的可能:abc
3取2的可能:ab ac bc
3取1的可能:a b c
排列模板代碼
/**
* @author god-jiang
* @date 2020/3/23 14:31
*/
public class Permutation {
//全排列
public static void perm(char[] arr, int start, int len) {
if (start == len - 1) {
for (int i = 0; i < len; i++) {
System.out.print(arr[i]);
}
System.out.println();
} else {
for (int i = start; i < len; i++) {
swap(arr, start, i);
perm(arr, start + 1, len);
swap(arr, start, i);
}
}
}
//交換兩個數
public static void swap(char[] arr, int i, int j) {
char temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
public static void main(String[] args) {
char[] arr = "abc".toCharArray();
perm(arr, 0, arr.length);
}
}
組合模板代碼
import java.util.Arrays;
/**
* @author god-jiang
* @date 2020/3/23 14:57
*/
public class Combination {
public static void combination (char[] input, char[] output, int index, int start) {
if (index == output.length) {
System.out.println(Arrays.toString(output));
} else {
for (int j = start; j < input.length; j++) {
output[index] = input[j];
combination (input, output, index + 1, j + 1);
}
}
}
public static void main(String[] args) {
char[] input = "abc".toCharArray();
//N表示組合中取幾位數
int N = 2;
char[] output = new char[N];
combination (input, output, 0, 0);
}
}
PS:一般比賽或者筆試都可以直接當作模板來使用。就好比,藍橋杯比賽和牛客網筆試要帶輸入輸出模板一樣。然後就是希望對你們有所幫助。