在Java中,我们可以利用递归和分治策略来解决这些问题:
1) **递归:**
- **整数划分问题**(如找所有加法组合使得总和等于目标值,可以用回溯法或递归):
```java
public List<List<Integer>> combinationSum(int[] nums, int target) {
List<List<Integer>> res = new ArrayList<>();
helper(nums, target, 0, new ArrayList<>(), res);
return res;
}
private void helper(int[] nums, int target, int start, List<Integer> path, List<List<Integer>> res) {
if (target == 0) {
res.add(new ArrayList<>(path));
} else if (target < 0 || start >= nums.length) {
return;
} else {
// 正向添加
path.add(nums[start]);
helper(nums, target - nums[start], start + 1, path, res);
// 回溯
path.remove(path.size() - 1);
// 反向添加
helper(nums, target, start + 1, path, res);
}
}
- **汉诺塔问题**(将A塔的n个盘子移动到C塔,中间B塔不可用):
```java
public void hanoi(int n, char from, char to, char aux) {
if (n > 0) {
hanoi(n - 1, from, aux, to);
System.out.println("Move disk " + n + " from " + from + " to " + to);
hanoi(n - 1, aux, to, from);
}
}
```
2) **分治:**
- **递归实现快速排序**:
```java
public void quickSort(int[] arr, int low, int high) {
if (low < high) {
int pivotIndex = partition(arr, low, high);
quickSort(arr, low, pivotIndex - 1);
quickSort(arr, pivotIndex + 1, high);
}
}
private int partition(int[] arr, int low, int high) {
int pivot = arr[high];
int i = low - 1;
for (int j = low; j < high; j++) {
if (arr[j] <= pivot) {
i++;
swap(arr, i, j);
}
}
swap(arr, i + 1, high);
return i + 1;
}
- **递归实现合并排序**:
```java
public void mergeSort(int[] arr, int left, int right) {
if (left < right) {
int mid = left + (right - left) / 2;
mergeSort(arr, left, mid);
mergeSort(arr, mid + 1, right);
merge(arr, left, mid, right);
}
}
private void merge(int[] arr, int left, int mid, int right) {
int[] temp = new int[right - left + 1];
int i = left, j = mid + 1, k = 0;
while (i <= mid && j <= right) {
if (arr[i] <= arr[j]) {
temp[k++] = arr[i++];
} else {
temp[k++] = arr[j++];
}
}
while (i <= mid) {
temp[k++] = arr[i++];
}
while (j <= right) {
temp[k++] = arr[j++];
}
System.arraycopy(temp, 0, arr, left, temp.length);
}
```