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

相关推荐

PyCharm旧版本下载地址

快捷找到PyCharm历史版本下载地址

piaopiaolanghua的专栏 4434

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

element的el-cascader组件动态加载,以及报错处理问题

Blocked aria-hidden on an element because its descendant retained focus. The focus must not be hidden from assistive technology users. 报错处理

weixin_56527169的博客 1262

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

CAN 比特率和采样点计算

架构根据输入频率和比特率自动计算。

ldinvicible的专栏 787

新手小白如何学习编程

学习目标推荐第一门语言优势网站 / APP 开发(前端)JavaScript浏览器原生支持,能快速做出可视化效果后端 / 服务器 / 数据分析Python语法简洁像英语,库多、应用广(入门友好)游戏开发先用电竞入门,再转专业引擎硬件 / 嵌入式(比如单片机)C 语言贴近硬件,行业标准办公自动化(Excel / 文档处理)Python快速解决重复工作(比如批量改文件)👉新手首选推荐。

2501_94331842的博客 2232

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

【Windows Server 2019】组策略的配置与管理——理论基础

博文介绍了组策略的定义,作用和分类。组策略包括计算机配置和用户配置;组策略又分为为基于本地的组策略和基于AD(活动目录)的域组策略。并说明了不同组策略发生冲突时默认的规则。

VMware, Windows, Linux, Cisco, Container, Kubernetes, Kali 1万+

[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

【100%通过率】2023华为od机试C卷【电脑病毒感染】C++ 实现

一个局域网内有很多台电脑,分别标注为 0 ~ N-1 的数字。相连接的电脑距离不一样,所以感染时间不一样,感染时间用t 表示。其中网络内一台电脑被病毒感染,求其感染网络内所有的电脑最少需要多长时间。如果最后有电脑不会感染,则返回-1.

MISAYAONE的博客 1727

PR工具timing report中setup time的计算过程

然后去pr工具里报告report_delay_calculation/reportDelayCalculation -from related_pin -to constraint_pin。这里constraint pin就是D pin (D0 D1 D2 D3),related pin就是 CK pin。我正在「拾陆楼」和朋友们讨论有趣的话题,你⼀起来吧?

m0_61544122的博客 455

[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

纳米尺度仿真软件:Quantum Espresso_(13).非线性光学性质计算

通过 Quantum Espresso,可以高效地计算材料的非线性光学性质,包括二阶和三阶非线性极化率。这些性质在许多现代技术中具有重要的应用价值。在准备输入文件时,需要详细描述系统的晶格结构和原子位置,选择合适的基组和赝势,并设置计算参数和微扰设置。通过优化计算参数和使用并行计算,可以提高计算效率和精度。最后,使用适当的工具进行结果分析和可视化,可以更好地理解材料的非线性光学行为。

kkchenjj的博客 1278

38_StringPermutation(字符串排序)

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

Alatebloomer的博客 629

怀旧版电脑GBC模拟器

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

精雕软件(JDpaint) 5.5 绿色版

精雕软件(JDpaint) 5.5 绿色版精雕软件(JDpaint) 5.5 绿色版精雕软件(JDpaint) 5.5 绿色版

Java练习:排列(Permutation)问题

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

yqj2065的博客 2542

SAP B1中文培訓教材_SDK

公司内部培训资料,对开发工具 ,DIAPI, UIAPI,Add-ON有详细解说

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

TMS_WebGMaps_1.9.8.0_Full_Source

TMS_WebGMaps_1.9.8.0_Full_Source 全源码 delphi cbuilder

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

余额充值