Recursion 字符串的全排列 String Permutation @CareerCup

Permutation递归解法 permutation类型题的解法 阅读详情

字符串全排列的题目,还是套用模板,同样要注意ret的size问题会变化。而且与上一题不同的是不光是要在ret后面添加进新的组合,而且还要移除前面用过的组合。类似一个队列。


另外Java的substring中区间闭合情况是左闭右开 [ ) 所以想把一个字符串拆成两个区间就可以用这一句:

for(int j=0; j<=tmp.length(); j++){		
	// substring区间: [)
	ret.add(tmp.substring(0, j) + head + tmp.substring(j));
}



思路还是按照这里写的:http://hawstein.com/posts/8.4.html

思路一:

我们可以把串“abc”中的第0个字符a取出来,然后递归调用permu计算剩余的串“bc” 的排列,得到{bc, cb}。然后再将字符a插入这两个串中的任何一个空位(插空法), 得到最终所有的排列。比如,a插入串bc的所有(3个)空位,得到{abc,bac,bca}。 递归的终止条件是什么呢?当一个串为空,就无法再取出其中的第0个字符了, 所以此时返回一个空的排列。



思路二:

我们还可以用另一种思路来递归解这个问题。还是针对串“abc”, 我依次取出这个串中的每个字符,然后调用permu去计算剩余串的排列。 然后只需要把取出的字符加到剩余串排列的每个字符前即可。对于这个例子, 程序先取出a,然后计算剩余串的排列得到{bc,cb},然后把a加到它们的前面,得到 {abc,acb};接着取出b,计算剩余串的排列得到{ac,ca},然后把b加到它们前面, 得到{bac,bca};后面的同理。最后就可以得到“abc”的全序列。



package Recursion;

import java.util.ArrayList;

/**
 * Write a method to compute all permutations of a string
 * 
 *  写一个函数返回一个串的所有排列
 *
 */
public class S9_5 {

	public static void main(String[] args) {
		ArrayList<String> list = getPerms("abc");
		System.out.println("There are " + list.size() + " permutations.");
		for (String s : list) {
			System.out.println(s);
		}
	}

	// ========================================= 方法一
	/*
	 *	ABC:
	 *
	 *	A -> [BC]:
	 *		ABC, BAC, BCA
	 *
	 * A -> [CB]
	 * 		ACB, CAB, CBA
	 */
	public static ArrayList<String> getPerms(String str) {
		ArrayList<String> ret = new ArrayList<String>();
		rec(str, 0, ret);
		return ret;
	}
	
	public static void rec(String str, int start, ArrayList<String> ret){
		if(start == str.length()){
			ret.add("");				// Basecase总是要插入一个空字符串
			return;
		}
		
		rec(str, start+1, ret);	// 处理子问题
		int size = ret.size();		// 还是因为ret长度会变化所以记录在size变量中
		String head = str.substring(start, start+1);
		for(int i=0; i<size; i++){
			String tmp = ret.get(0);		// 从ArrayList头取出,并删除
			ret.remove(0);
			for(int j=0; j<=tmp.length(); j++){		// 加到ArrayList后头
				// substring区间: [)
				ret.add(tmp.substring(0, j) + head + tmp.substring(j));
			}
		}
	}
	
	//================================= 另一种方法二
	public static ArrayList<String> getPerms2(String str){
		ArrayList<String> ret = new ArrayList<String>();
		rec2("", str, ret);
		return ret;
	}
	
	/*
	 * ABC:
	 * 
	 * (A,BC)
	 * 		(AB,C)
	 * 			(ABC,)
	 * 		(AC,B)
	 * 			(ACB,)
	 * 
	 * (B,AC)
	 * 		(BA,C)
	 * 			(BAC,)
	 * 		(BC,A)
	 * 			(BAC,)
	 * 
	 * (C,AB)
	 * 		(CA,B)
	 * 			(CAB,)
	 * 		(CB,A)
	 * 			(CBA,)
	 *   
	 */
	// done: 已经完成部分,rest:尚未完成部分
	public static void rec2(String done, String rest, ArrayList<String> ret){
		if(rest.length() == 0){
			ret.add(new String(done));
			return;
		}
		
		// 遍历rest的所有字符,每次选择一种结合到done,rest去掉被选择的那个字符
		for(int i=0; i<rest.length(); i++){
			rec2(done+rest.charAt(i), rest.substring(0, i)+rest.substring(i+1), ret);
		}
	}

}


针对第二种方法,再补充一种用StringBuilder的方法,因为StringBuilder可以很方便地对字符串修改,特别记住以下StringBuilder函数:

public StringBuilder insert(int offset,
                   char c)

public StringBuilder deleteCharAt(int index)

public StringBuilder append(char c)


public static void main(String []args){
        String s = "abcdefg";
        rec(new StringBuilder(), new StringBuilder(s));
    }
     
    
    public static void rec(StringBuilder done, StringBuilder rest){
        if(rest.length() == 0) {
            System.out.println(done.toString());
            return;
        }
        
        for(int i=0; i<rest.length(); i++) {
            char c = rest.charAt(i);
            done.append(c);
            rest.deleteCharAt(i);
            rec(done, rest);
            rest.insert(i, c);
            done.deleteCharAt(done.length()-1);
        }
    }




PS1:Generate all the strings of n bits, Assume A[0...n-1] is an array of size n.

public class HelloWorld{

     public static void main(String []args){
        bin(3);
     }
     
     static char[] ss = {0,0,0};
     
     public static void bin(int len){
         if(len == 0) {
             System.out.println(new String(ss));
             return;
         }
         
         ss[len-1] = '0';
         bin(len-1);
         ss[len-1] = '1';
         bin(len-1);
     }
}

得出结果:

000
100
010
110
001
101
011
111

PS2: Generate all the string of length n drawn from 0...k-1

public class HelloWorld{

     public static void main(String []args){
        int len = 3; 
        // bin(len);
        k_bin(len, 5);
     }
     
     static char[] ss = {0,0,0};
     
     public static void bin(int len){
         if(len == 0) {
             System.out.println(new String(ss));
             return;
         }
         
         ss[len-1] = '0';
         bin(len-1);
         ss[len-1] = '1';
         bin(len-1);
     }
     
     
     public static void k_bin(int len, int k) {
         if(len == 0) {
             System.out.println(new String(ss));
             return;
         }
         
         for(int i=0; i<k; i++) {
             ss[len-1] = (char)(i+'0');
             k_bin(len-1, k);
         }
     }
}


000
100
200
300
400
010
110
210
310
410
020
120
220
320
420
030
130
230
330
430
040
140
240
340
440
001
101
201
301
401
011
111
211
311
411
021
121
221
321
421
031
131
231
331
431
041
141
241
341
441
002
102
202
302
402
012
112
212
312
412
022
122
222
322
422
032
132
232
332
432
042
142
242
342
442
003
103
203
303
403
013
113
213
313
413
023
123
223
323
423
033
133
233
333
433
043
143
243
343
443
004
104
204
304
404
014
114
214
314
414
024
124
224
324
424
034
134
234
334
434
044
144
244
344
444








StringPermutation:创建字符串的排列并按字母顺序返回 StringPermutation 立即下载

相关推荐

Gromacs实战:从蛋白质-小分子对接到分子动力学模拟全流程解析

本文详细解析了使用Gromacs进行蛋白质-小分子复合物分子动力学模拟的全流程。从处理AutoDock等对接软件的结果文件开始,逐步指导如何为蛋白质和小分子分别生成拓扑文件,并解决力场合并的核心挑战。文章涵盖了构建模拟盒子、添加溶剂离子、能量最小化、平衡模拟以及关键的轨迹分析步骤,为计算生物学和药物设计研究者提供了一套从静态对接到动态评估的完整实战指南。

weixin_29251337的博客 1218

String Permutation java solution

description: Given two strings, write a method to decide if one is a permutation of the other.Have you met this question in a real interview? Yes Example abcd is a permutation of bcad, but abbe is n

ncst 459

VSCode+PlatformIO新建工程卡成狗?3步提速大法实测有效(附镜像源配置)

针对VSCode+PlatformIO新建工程时因依赖下载缓慢导致的加载慢问题,本文提供了三步核心提速方案。通过配置Python环境变量、修改PlatformIO插件设置以使用国内镜像源,并优化pip配置文件,实测可大幅缩短工程创建时间,有效解决创建工程卡顿的痛点。

delta的博客 711

LintCode-10: String Permutation II (经典DFS排列题)

这题就是经典DFS排列(Permutation)题。 注意: 1)既然是Permutation,就要先sort,并加visited[]。而input是个string,所以要把string变成vector&lt; char &gt;才能sort。 2) 注意去重的关键一步。 if ((i &gt; 0) &amp;&amp; (str[i] == str[i - 1]...

roufoo的博客 792

保姆级教程:用ncnn把自训练的YOLOv8模型塞进Android App(附完整代码)

本文提供了一份详细的保姆级教程,指导开发者如何将自训练的YOLOv8模型通过ncnn框架部署到Android应用中。教程涵盖环境配置、模型训练与转换、Android工程集成及性能优化等全流程,并附完整代码实现,帮助开发者快速掌握移动端AI模型部署技术。

weixin_42659194的博客 255

磁栅尺的基本原理

一、磁栅尺简介 磁栅尺(Magnetic scale)是一种常见于工业自动化设备领域的线性位移测量方案,因为其耐用性强,对环境要求不高,逐渐替代了对环境要求苛刻的光学直线测量方案。 作为自动化设备领域里不多见的精密位移检测方案,磁栅尺使用广泛,尤其适用于检测行程长、测量精度要求高、工况复杂的大型机床。磁栅尺安装方便,抗干扰能力强,抗冲击性强,不易受到振动、粉尘、水垢、油污等影响,耐高温和耐低温性能也较为突出。 二、磁栅尺基本组成与原理 磁栅尺主要由两个部分组成,磁尺和读磁头。 磁尺 磁尺是磁栅尺

Luckboy_shy的博客 1万+

27_PermutationString

Permutation:排列 package swordToOffer._27_PermutationString; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; /* 题目描述: 输入一个字符串,按字典序打印出该字符串...

weixin_44683593的博客 207

VS2019 +osg3.6.5+ earth3.2+qt5.14.2+osgQt 编译教程

用vs新建工程,稍后会在写一篇博客上分享四、结语至此,所有的编译就均已完成。

king_ink的博客 1134

[CareerCup] 1.3 Permutation String 字符串的排列

  1.3 Given two strings, write a method to decide if one is a permutation of the other.   这道题给定我们两个字符串,让我们判断一个是否为另一个的全排列字符串。在LeetCode中,关于排列的题有如下几道,Permutation Sequence 序列排序,Permutations 全排列, Permut...

weixin_34029680的博客 181

【机械臂视觉抓取从理论到实战】

首先声明一下,此项目是参考B站哈萨克斯坦UP的【机械臂视觉抓取从理论到实战】 此内容为他研究生生涯的阶段性成果展示和技术分享,所有数据和代码均开源。所以鹏鹏我特此来复现一下,我采用的硬件与之有所不同,UP主使用UR5,我实验室采用的是UR3,下面列出相关材料 UR3CB3.12:https://www.universal-robots.cn/cb3/ 【UR3系统升级到CB3.12附带URcap1.05】硬件支持代码支持 jacquard数据集:https://pan.baidu.com/s/1524HrV

vor234的博客 5184

【人工智能】《Deep Dive into LLMs like ChatGPT 》—— Andrej Karpathy 第三阶段:强化学习(Reinforcement Learning, RL)

摘要:强化学习(RL)阶段通过让模型自主生成并验证答案,突破SFT阶段的模仿局限,使其在数学、代码等领域形成独特的推理路径。RL流程包括批量生成解答、自动批改筛选正确路径,并采用PPO/GRPO算法优化模型。模型会自发涌现自我检查、回滚等策略,显著提升正确率(如AIME竞赛准确率从15%升至56%)。与SFT模型相比,RL模型具备主动链式思维、验算能力,响应时间更长但效果更优,形成真正的“思考模型”。三阶段对比显示,RL通过可验证题的对错奖励机制,赋予模型超越人类范式的推理能力。

奶爸的编程之路,也就一周冷个三天 149

[LintCode] 字符串置换 String Permutation

给定两个字符串,请设计一个方法来判定其中一个字符串是否为另一个字符串的置换。 置换的意思是,通过改变顺序可以使得两个字符串相等。样例 “abc” 为 “cba” 的置换。 “aabc” 不是 “abcc” 的置换。Given two strings, write a method to decide if one is a permutation of the other. Example

wutingyehe的专栏 3458

【AI Agent】Hermes Agent解析

Hermes Agent:一个具备持久化学习能力的开源AI Agent框架 核心特点: 突破传统Agent的"无状态困境",通过记忆系统(SQLite+FTS5全文检索)实现跨会话经验积累 支持200+模型自由切换,11种模型家族和15+平台接入 五层架构设计(入口层、编排层、推理层、工具执行层、存储层)实现平台无关性 47+内置工具和动态技能沉淀机制,支持从任务执行中自动提炼可复用Skill 独特的四层记忆体系(会话/每日/长期/向量索引)和辩证式用户建模 与传统Agent对比: 具备自我进化能力,通过A

sysu_lluozh 928

38_StringPermutation(字符串排序)

题目描述输入一个字符串,按字典序打印出该字符串中字符的所有排列。例如输入字符串abc,则打印出由字符a,b,c所能排列出来的所有字符串abc,acb,bac,bca,cab和cba。输入描述:输入一个字符串,长度不超过9(可能有字符重复),字符只包括大小写字母。解题思路:先算出所有的情况,在利用字典排序进行排序,字典排序算法如下: 一般而言,设P是[1,n]的一个全排列。      P=P1P2…...

Alatebloomer的博客 629

win10 跳过U8环境检测的IE WebControls.rar

win10 安装u8的时候 提示IE WebControls 不通过,这个工具可以欺骗u8的检查。 跳过U8环境检测的IE WebControls。提示导入失败后,重新检测通过。

复分析 阿尔福斯(Ahlfors) 第三版答案 英文

答案分为十章,有部分习题没有答案,全英文复分析阿尔福斯(Ahlfors) 第三版答案

Java练习:排列(Permutation)问题

按照排列组合,可知全排列个数为n!

yqj2065的博客 2542

visio安装包

Microsoft Office Visio 是一款专业的制图软件。利用经过更新的形状、协作工具和数据链接图表,创建专业级图表以简化复杂的信息。

StringPermutation

#include void Permutation(char* pStr,char* begin){ if(*begin=='\0') printf("%s\n",pStr); else{ for(char* ch=begin;*ch!='\0';ch++){ char temp=*begin; *begin=*ch; *ch=temp; Permutation

静思致远 495

java recursion_在Java中使用recursion来反转string

该函数采用String的第一个字符 – str.charAt(0) – 将其放在最后,然后调用自己 – reverse() – 其余部分 – str.substring(1) ,将这两个东西加在一起得到结果 – reverse(str.substring(1)) + str.charAt(0)当传入的string是一个字符或更less,所以不会有剩余 – 当str.length() <= 1...

weixin_32258691的博客 235

string字符串转实体类_【Recursion】(6)实战练习:使用递归处理字符串

使用递归清除字符串中的" "和/tdef remove(string): # Base Case if not string: return "" # Recursive Case if string[0] == "t" or string[0] == " ": return remove(string[1:]) else: return ...

weixin_39716043的博客 173

Permutations II Java

Given a collection of numbers that might contain duplicates, return all possible unique permutations. For example, [1,1,2] have the following unique permutations: [1,1,2], [1,2,1], and [2,1,1

喜欢反对 570

剑指offer|字符串的排列

【题目描述】 输入一个字符串,按字典序打印出该字符串中字符的所有排列。例如输入字符串abc,则打印出由字符a,b,c所能排列出来的所有字符串abc,acb,bac,bca,cab和cba。 输入描述: 输入一个字符串,长度不超过9(可能有字符重复),字符只包括大小写字母。 时间限制:1秒 空间限制:32768K 热度指数:378352 本题知识点: 字符串 【解题思路】 把字符串分为两部分:一部分...

笔记本 8238

Permutation in String

Given two strings s1 and s2, write a function to return true if s2 contains the permutation of s1. In other words, one of the first string's permutations is the substring of the second string. Ex

DDVAL的博客 721

Backtracking

1. Introduction Backtracking is a method of exhaustive search. When a node reaches certain termination condition that means this path will not have solutions, the program will go back to the previous

NoviceSi的博客 447

字符全排列Permutation

题目:给定字符串,输出全排列的所有结果。例如abc则需要输出abc,acb,bac,bca,cab,cba。 具体代码如下 // 如果需要把所有的可能都打印出来,不管是否有重复,就是用List,否则如果需要去除重复,可以使用Set private List lst =

lichong_87的备忘录 983

38_StringPermutation

package pers.lyt.java; import java.util.ArrayList; import java.util.Collections; //题目  // 输入一个字符串,打印出该字符串中字符的所有排列。例如输入字符串abc,则打印出由 //字符a、b、c所能排列出来的所有字符串abc、acb、bac、bca、cab和cba。(本文代码采用 //ArrayList&lt...

StackOverflow的博客 180
上一篇: Recursion 求所有子集 @CareerCup
下一篇: Recursion n对括号的组合 @CareerCup
chiiis
博客等级 码龄14年 422粉丝 429原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值