给一个3位长的整型数组,判断这三个数是否通过加减乘3种运算得到数12。 [1, 1,1] : false [3,4,5]: true [4,8,5]: true [4,4,4]: true 用java代码实现
时间: 2024-04-14 09:30:36 浏览: 7
可以使用递归来实现对数组进行加减乘3种运算的组合判断。以下是一个Java代码示例:
```java
public class Main {
public static void main(String[] args) {
int[] nums1 = {1, 1, 1};
int[] nums2 = {3, 4, 5};
int[] nums3 = {4, 8, 5};
int[] nums4 = {4, 4, 4};
System.out.println(canReachTarget(nums1, 0, 0));
System.out.println(canReachTarget(nums2, 0, 0));
System.out.println(canReachTarget(nums3, 0, 0));
System.out.println(canReachTarget(nums4, 0, 0));
}
public static boolean canReachTarget(int[] nums, int currentIndex, int currentSum) {
if (currentIndex == nums.length) {
return currentSum == 12;
}
int num = nums[currentIndex];
// 加法运算
if (canReachTarget(nums, currentIndex + 1, currentSum + num)) {
return true;
}
// 减法运算
if (canReachTarget(nums, currentIndex + 1, currentSum - num)) {
return true;
}
// 乘法运算
if (canReachTarget(nums, currentIndex + 1, currentSum * num)) {
return true;
}
return false;
}
}
```
这段代码中,`canReachTarget` 方法使用递归的方式进行判断。其中,`currentIndex` 表示当前处理的数组元素索引,`currentSum` 表示当前的运算结果。如果遍历到数组末尾时,`currentSum` 等于 12,则返回 `true`;否则,尝试进行加减乘三种运算,并递归调用 `canReachTarget` 方法继续判断。如果有一种运算能够得到结果为 12,则返回 `true`;否则,返回 `false`。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![ppt](https://img-home.csdnimg.cn/images/20210720083527.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)