请用java另一种解法
时间: 2024-04-16 14:27:04 浏览: 26
以下是另一种使用Java编写的解法,用于打印出四个字母(A、B、C、D)的所有四位不相同的组合:
```java
public class Combination {
public static void main(String[] args) {
String letters = "ABCD";
generateCombination(letters, "");
}
public static void generateCombination(String letters, String combination) {
if (combination.length() == 4) {
System.out.println(combination);
return;
}
for (int i = 0; i < letters.length(); i++) {
char letter = letters.charAt(i);
// 检查当前字母是否已经在组合中
if (combination.indexOf(letter) == -1) {
generateCombination(letters, combination + letter);
}
}
}
}
```
运行上述代码将会输出所有不相同的四位组合,例如:
```
ABCD
ABDC
ACBD
ACDB
ADBC
ADCB
BACD
BADC
BCAD
BCDA
BDAC
BDCA
CABD
CADB
CBAD
CBDA
CDAB
CDBA
DABC
DACB
DBAC
DBCA
DCAB
DCBA
```
希望对你有所帮助!如果还有其他问题,请随时提问。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)