编程列出一个字符串的全字符组合情况,原始字符串中没有重复字符

编程列出一个字符串的全字符组合情况,原始字符串中没有重复字符,
 例如:原始字符串是"abc",
 打印得到下列所有组合情况:
 "a" "b" "c"
 "ab" "bc" "ca" "ba" "cb" "ac"

 "abc" "acb" "bac" "bca" "cab" "cba"

此题采用排列组合的算法

摘自网路

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class Plzh {
    private static char[] is ;
    private static int total;
    private static int m;
    public static void main(String[] args) {
    	Scanner sc = new Scanner(System.in);
        List<Integer> iL = new ArrayList<Integer>();
        System.out.println("请输入一串字符");
        String next = sc.next();
        is = next.toCharArray();
        m=next.length();
        for (int i = 1; i <= m; i++) {
        	 new Plzh().plzh("", iL,  i);
        	 System.out.println();
		}
        System.out.println("total : " + total);
    }
    private void plzh(String s, List<Integer> iL, int m) {
        if(m == 0) {
            System.out.print(s+"\t");
            total++;
            return;
        }
        List<Integer> iL2;
        for(int i = 0; i < is.length; i++) {
            iL2 = new ArrayList<Integer>();
            iL2.addAll(iL);
            if(!iL.contains(i)) {
                String str = s + is[i];
                iL2.add(i);
                plzh(str, iL2, m-1);
            }
        }
    }
}

改编

import java.util.Scanner;
public class Group {
    private static char[] is ;
    private static int total;
    public static void main(String[] args) {
    	Scanner sc = new Scanner(System.in);
        StringBuilder sb = new StringBuilder();
        System.out.println("请输入一串字符");
        String next = sc.next();
        is = next.toCharArray();
        int m=next.length();
        for (int i = 1; i <= m; i++) {
        	group("", sb,  i);
        	 System.out.println();
		}
        System.out.println("total : " + total);
    }
    public static void group(String s, StringBuilder sb, int m) {
        if(m == 0) {
            System.out.print(s+"\t");
            total++;
            return;
        }
        StringBuilder sb2;
        for(int i = 0; i < is.length; i++) {
        	sb2 = new StringBuilder();
        	sb2.append(sb);
            if(sb.indexOf(String.valueOf(i))==-1) {
                String str = s + is[i];
                sb2.append(i);
                group(str, sb2, m-1);
            }
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值