剑指Offer——全排列递归思路_0_10_全排列 剑指offer

我们可以看到,这里的孩子个数是递减的,直到最后一个元素,就不用选择了,同时也得到一种可能。

要枚举出所有的,那么就遍历这样一颗树。好了,先上代码。

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)


  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值