ch8-4: find the permutations of a string

本文介绍了一种计算字符串所有可能排列的方法,提供了两种递归实现方案:一种是通过移除字符并将其置于排列结果的开头;另一种是在已知较短字符串排列的基础上插入额外的字符。此外,还提供了一个简洁的Java实现示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

This is a similar problem to ch 8.3.

In recursion, we can think a little bit different: so here are two recursion version:

method 1: perm("abc") can remove "a" and put at the Beginning of perm("bc"), then remove "b" to put at the Beginning of perm("ac")....

method 2: perm("abc") can be divided to perm("bc") then put "a“ in anywhere of ”bc";



//Write a method to compute all permutations of a string
// http://www.chaozh.com/cracking-the-coding-interview-q7-12/

#include 
#include 
#include 

using namespace std;

typedef vector vs;

// method 1: HAWSTEIN
vs perm(string s){
    vs result;
	if(s==""){
		result.push_back("");
		//return result;
	}
	for(int i =0; i

Also, here is the Java solution: Very short.

public class Permutation {
//https://gist.github.com/xuyirio/3029161 
    public static void permutateString(String s, String tgs){
		int last = tgs.length();
 
		if (last == 0){
			System.out.println(s);
			return;
		}
		
		for (int i = 0; i < last; i++ ){
			permutateString(s + tgs.charAt(i), tgs.substring(0, i) + tgs.substring(i+1));
		}
	}
 
	public static void main(String[] args) {
		permutateString("", "112");
 
	}
 
}

/*
112
121
112
121
211
211
*/


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值