java输出字符串的所有排列

昨天开始看《数据结构与算法分析_java语言描述》这本书,第一章的习题1.6 让我想了老半天,网上查了下发现解决方法蛮多的,用的都是递归,不禁感慨算法真是太神奇了- -

so 在这里记录一下我找到的几个解决方法。

 

第一种:

	public static List<String> pailie(String str){
		List<String> result = new ArrayList<String>();
		
		if(str.length()==1) result.add(str);
		else {
			char thisChar = str.charAt(0);
			List<String> temp = pailie(str.substring(1));
			for(int i =0;i<temp.size();i++){
				String thisStr = temp.get(i);
				for(int j=0 ; j<= thisStr.length() ; j++){
					String firstStr = thisStr.substring(0, j);
					String lastStr = thisStr.substring(j);
					result.add(firstStr + thisChar + lastStr);
				}
			}
		}
		return result;
	}

	public static void main(String[] args) {
		List<String> newList = pailie("abcd");
		for(String temp : newList){
			
			System.out.println(temp);
			
		}
		System.out.println("-----------------------------------");
		System.out.println(newList.size());
	}


 

第二种:

    public static void main(String[] args) {
        String str = "abc";
        permutation(str.toCharArray(), 0);
    }

    public static void permutation(char[] str, int i) {
        if (i >= str.length)
            return;
        if (i == str.length - 1) {
            System.out.println(String.valueOf(str));
        } else {
            for (int j = i; j < str.length; j++) {
                char temp = str[j];
                str[j] = str[i];
                str[i] = temp;

                permutation(str, i + 1);

                temp = str[j];
                str[j] = str[i];
                str[i] = temp;
            }
        }
    }


 

第三种:

	public static int c = 0;
    
    public static void main(String[] args) {
        String s = "abcd";
        printAllArray(s, "");
    }

    private static void printAllArray(String s, String n) {
        if (s.length() == 0) {
            System.out.println(n + "  ---  " + ++c);
        } else {
            for (int i = 0; i < s.length(); ++i) {
                printAllArray(s.substring(1), n + s.charAt(0));
                s = s.substring(1) + s.charAt(0);
            }
        }
    }


 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值