字符串全排列

本文详细介绍了使用Java实现全排列及其去重的方法,通过递归调用和交换字符来完成全排列,并利用isSwap方法检测并跳过重复元素,最后输出所有不重复的排列结果。

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

package com.vic.string;

public class Permutation {
	private static int count = 0;
	static void permutation(char[] s,int start){
		if(start==s.length){
			System.out.println(new String(s).toString());
			count++;
		}
		for(int i=start;i<s.length;i++){
			//第一个字符和后面每一个分别交换
			char temp = s[i];
			s[i] = s[start];
			s[start] = temp;
			
			permutation(s,start+1);//向后递归
			//换回来
			s[start] = s[i];
			s[i] = temp;
		}
	}
	
	public static void main(String[] args) {
		char[] s = "abc".toCharArray();
		permutation(s, 0);
		System.out.println("total:"+count);
	}
}
//除去重复元素的全排列
public class ListAll {
	private static int count =0;
	public static void list(int[] a,int start,int end){
		if (start==end) {
			display(a);
			count++;
			return;
		}else{
			for (int i = start; i <= end; i++) {
				if (isSwap(a,start,i)) {
					int temp = a[start];
					a[start] = a[i];
					a[i] = temp;
					list(a, start+1, end);
					a[i] = a[start];
					a[start] = temp;
				}
			}
		}
	}
	

	private static boolean isSwap(int[] a, int start, int i) {
		for (int j = start; j < i; j++) {
			if (a[j] == a[i]) {
				return false;
			}
		}
		return true;
	}


	private static void display(int[] a) {
		for (int i = 0; i < a.length; i++) {
			
			System.out.print(a[i]+" ");
		}
		System.out.println();
	}

	public static void main(String[] args) {
		int[] a = {1,1,2,3};
		list(a, 0, a.length-1);
		System.out.println(count);
		
	}
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值