zoukankan      html  css  js  c++  java
  • 字符串全排列Java实现

    字符串全排列Java实现

    陷阱:
    注意考虑有重复的情况,比如 a,b,b

    代码如下:
     1 package com.secbro.test;
     2 
     3 import java.util.ArrayList;
     4 import java.util.HashSet;
     5 import java.util.List;
     6 import java.util.Set;
     7 
     8 public class AllOrder {
     9 
    10     private static Set<String> result = new HashSet<String>();
    11 
    12     public static void main(String[] args) {
    13         char[] a = {'a','b','b'};
    14 
    15         permutation(a, 0, 2);
    16         System.out.println(result);
    17     }
    18 
    19 
    20     private static void permutation(char[] a, int from, int to) {
    21         if(a== null || from>to || from<0) {
    22             return;
    23         }
    24         if(from == to) {
    26             result.add(String.valueOf(a));
    27         }
    28         for(int i = from; i <= to; i++) {
    29             swap(a,i,from);
    30             permutation(a, from +1,to);
    31             swap(a,i,from);
    32         }
    33     }
    34 
    35 
    36     private static void swap(char[]a, int left, int right) {
    37         char temp = a[left];
    38         a[left] = a[right];
    39         a[right] = temp;
    40     }
    41 }

    执行代码结果

    [abb,  bba,  bab]

  • 相关阅读:
    SVG:中国地图
    网页编程工具:EditPlus
    js插件
    html: 仿制soundmanager2右上角面板
    代码:页面布局(含图片列表布局)
    写着玩: 图片 圆盘
    表格
    按钮
    插件:左侧下拉菜单
    颜色
  • 原文地址:https://www.cnblogs.com/wanghongsen/p/9208775.html
Copyright © 2011-2022 走看看