我们可以看到,这里的孩子个数是递减的,直到最后一个元素,就不用选择了,同时也得到一种可能。
要枚举出所有的,那么就遍历这样一颗树。好了,先上代码。
package cn.edu.ujn.nk;
public class FullPermutation {
/**
* recursive method, used for the tree traversal.
*
* @param inStr
* the elements need to be choose
* @param pos
* the position of the elements we choose
* @param parentData
* the elements have been chosen
*/
public void permutati
**真题解析、进阶学习笔记、最新讲解视频、实战项目源码、学习路线大纲**
**详情关注公中号【编程进阶路】**
on(String inStr, int pos, StringBuffer parentData) {
if (inStr.length() == 0) {
return;
}
if (inStr.length() == 1) {
System.out.println("{" + inStr + "}");
return;
}
// here we need a new buffer to avoid to pollute the other nodes.
StringBuffer buffer = new StringBuffer();
// copy from the parent node
buffer.append(parentData.toString());
// choose the element
buffer.append(inStr.charAt(pos));
// get the remnant elements.
String subStr = kickChar(inStr, pos);
// got one of the result
if (subStr.length() == 1) {
buffer.append(subStr);
System.out.println(buffer.toString());
return;
}
// here we use loop to choose other children.
for (int i = 0; i < subStr.length(); i++) {
permutation(subStr, i, buffer);
}
}
// a simple method to delete the element we choose
private String kickChar(String src, int pos) {
StringBuffer srcBuf = new StringBuffer();
srcBuf.append(src);
srcBuf.deleteCharAt(pos);
return srcBuf.toString();
}
public static void main(String args[]) {
FullPermutation p = new FullPermutation();
**读者福利**
========
> **由于篇幅过长,就不展示所有面试题了,想要完整面试题目的朋友(另有小编自己整理的2024大厂高频面试题及答案附赠)**
> ![](https://img-blog.csdnimg.cn/20201126205036657.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3NpbmF0XzM3OTAzNDY4,size_16,color_FFFFFF,t_70)
> ![](https://img-blog.csdnimg.cn/20201126205047777.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3NpbmF0XzM3OTAzNDY4,size_16,color_FFFFFF,t_70)
> ![](https://img-blog.csdnimg.cn/20201126205051391.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3NpbmF0XzM3OTAzNDY4,size_16,color_FFFFFF,t_70)