Java之回溯算法

回溯算法原理:

回溯算法实际上一个类似枚举的搜索尝试过程,主要是在搜索尝试过程中寻找问题的解,当发现已不满足求解条件时,就“回溯”返回,尝试别的路径。回溯法是一种选优搜索法,按选优条件向前搜索,以达到目标。但当探索到某一步时,发现原先选择并不优或达不到目标,就退回一步重新选择,这种走不通就退回再走的技术为回溯法,而满足回溯条件的某个状态的点称为“回溯点”。许多复杂的,规模较大的问题都可以使用回溯法,有“通用解题方法”的美称。

代码示例:

import java.util.Arrays;

public class Backtracking {
	// 回溯
	static void f(int a[], int k) {
		if (k == a.length - 1) {
			display(a);
			return;
		}
		for (int i = k; i < a.length; i++) {
			int temp = a[i];
			a[i] = a[k];
			a[k] = temp;

			f(a, k + 1);

			temp = a[i];
			a[i] = a[k];
			a[k] = temp;

		}
	}

	// 筛选
	static void display(int a[]) {
		System.out.println(Arrays.toString(a));

	}

	public static void main(String[] args) {
		// 要进行回溯的数组
		int[] a = new int[] { 1, 2, 3, 4, 5 };
		f(a, 0);
	}
}

输出结果:

[1, 2, 3, 4, 5]
[1, 2, 3, 5, 4]
[1, 2, 4, 3, 5]
[1, 2, 4, 5, 3]
[1, 2, 5, 4, 3]
[1, 2, 5, 3, 4]
[1, 3, 2, 4, 5]
[1, 3, 2, 5, 4]
[1, 3, 4, 2, 5]
[1, 3, 4, 5, 2]
[1, 3, 5, 4, 2]
[1, 3, 5, 2, 4]
[1, 4, 3, 2, 5]
[1, 4, 3, 5, 2]
[1, 4, 2, 3, 5]
[1, 4, 2, 5, 3]
[1, 4, 5, 2, 3]
[1, 4, 5, 3, 2]
[1, 5, 3, 4, 2]
[1, 5, 3, 2, 4]
[1, 5, 4, 3, 2]
[1, 5, 4, 2, 3]
[1, 5, 2, 4, 3]
[1, 5, 2, 3, 4]
[2, 1, 3, 4, 5]
[2, 1, 3, 5, 4]
[2, 1, 4, 3, 5]
[2, 1, 4, 5, 3]
[2, 1, 5, 4, 3]
[2, 1, 5, 3, 4]
[2, 3, 1, 4, 5]
[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