public class Recursive {
@Test
public void test() {
System.out.println("============Fibonacci " + Fibonacci(4));
System.out.println("============Factorial " + Factorial(5));
int[] array = {1,2,3};
FullSout(array,0,array.length);
}
//斐波那契數列 f(n) = f(n-1) +f(n-2)
//1 1 2 3 5 8 13...
public int Fibonacci(int n) {
if (n <= 1) return 1;
return Fibonacci(n - 1) + Fibonacci(n - 2);
}
//階乘n! n!=n*(n-1)*(n-2)...*1 => n!=n*(n-1)!
public int Factorial(int n) {
if (n <= 1) return 1;
System.out.print(n + "*");
return n * Factorial(n - 1);
}
//全排列
public void FullSout(int[] arr, int start, int end) {
//停止條件,說明已經到了最後一個元素
if(start==end){
for(int i=0;i<arr.length;i++){
System.out.print(arr[i]);
}
System.out.println();
return;
}
for(int i=start;i<end;i++){
//這裏交換是爲了把下一個元素提到最前面,
swap(arr,i,start);
//遞歸實現,在確定第一個元素的前提下,去做後面元素的全排列
FullSout(arr,start+1,end);
//元素復位,防止對下次循環造成影響
swap(arr,i,start);
}
}
public void swap(int[] arr, int start, int end) {
//簡單的元素交換
int temp = arr[start];
arr[start] = arr[end];
arr[end] = temp;
}
}