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 立即下载

相关推荐

Oracle19c-集群节点重新添加

Oracle RAC集群在极端情况下,如硬件、主机,集群软件损坏,导致集群节点永久无法使用,需要对集群节点进行修复,删除节点集群信息并重新加入集群,以恢复集群原有的架构。 本文主要讲述一套两节点的Oracle19c RAC集群,节点一orcl01由于主机异常无法正常启动,在对主机进行重装之后,需要将orcl01节点重新加入集群的操作步骤。环境信息: 操作系统:Linux 7 RAC集群:19C 主机节点:orcl0...

sinat_36757755的博客 2351

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

Pixhawk RPi CM4 Baseboard 树莓派CM4安装Ubuntu20.04 server 配置ros mavros mavsdk

cm4配置ros mavros连接pixhawk4 Pixhawk RPi CM4 Baseboard

baidu_41704597的博客 2127

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

别再纠结Dify了!实测对比RAGFlow和Dify,聊聊企业知识库到底该怎么选

本文深度对比了RAGFlow和Dify在企业知识库选型中的实际表现,从技术架构、性能指标、部署成本等多维度进行分析。RAGFlow在复杂文档处理和准确率方面表现突出,适合有专职技术团队的企业;而Dify则以低门槛和快速部署见长。文章提供了六维度评估法,帮助企业根据文档复杂度、准确率要求等技术指标做出明智选择。

weixin_30897233的博客 669

别只聊天了!手把手教你为Ollama+Open WebUI搭建本地知识库(基于BGE-M3和Qwen)

本文详细介绍了如何利用Ollama、Open WebUI和BGE-M3构建本地知识库,实现智能问答和文档检索。通过环境准备、文档处理、向量化实战和应用案例,帮助用户突破基础聊天场景,打造高效的个人知识管理体系。特别适合技术文档管理和学术研究场景。

weixin_42523720的博客 478

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

VisionMaster -Group循环、数组数据格式化

这里创建一个格式化工具,按照自己想要的模式格式化刚刚输出的数据。因为是检测多个物体,所以这里选择输出的是数组。第一次的模板很不满意,反复调整参数也没好,边缘不整齐,强迫症患者受不了。实测如果输入设置太多,会导致模块失效,所以尽量选择需要的少量参数。这里要打开循环使能,循环数值就是高精度匹配的匹配个数。Group输出设置里选择刚刚建立的数据集。左边是主流程,右边是组合模块内部流程。修改采图这里的曝光值,图像提亮一点。建一个数据集,把想要的数据收集起来。用TCP助手测试一下OK。成功得到了想要的数据。

weixin_69505365的博客 4530

[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

DO-178C详解:机载软件开发、验证与适航标准指南

DO-178C将软件划分为五个等级(A到E),这些等级是基于失效状态对航空器安全的影响而定。

qq_41854911的博客 2848

C++软件异常分析概述

本文将详细讲述Windows系统中软件异常的分类以及常用的排查方法,给大家提供一个借鉴与参考。

dvlinker的技术专栏 4万+

[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

ESP32设备驱动-TM1637-驱动4位7段数码管

TM1637是一款带键盘扫描接口的LED(发光二极管显示器)驱动控制专用电路,内部集成了MCU数字接口、数据锁存、LED高压驱动、键盘扫描等功能。 TM1637使用DIP20/SOP20封装,主要适用于电磁炉、微波炉、小家电的显示驱动。

视觉与物联智能 2117

38_StringPermutation(字符串排序)

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

Alatebloomer的博客 629

NTscan扫描工具

ntscan是一个扫描器,可以扫描没有密码和弱密码的共享,先到配置文件中填写猜测的用户名和密码,扫描过程中右侧出现的是扫描日志。

怀旧版电脑GBC模拟器

再现原版GBC掌机的界面,电脑运行连游戏界面都一样大小,很怀旧,很真实,(英文版)强烈推荐,很小的文件,很难才找到的。

Java练习:排列(Permutation)问题

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

yqj2065的博客 2542

汉书HE8,好用的汇编代码编写工具

汉书HE8,好用的汇编代码编写工具早期编写汇编代码所用功能强大

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、付费专栏及课程。

余额充值