废了很大的劲写了一个获取任意字符串得A(M,N)得结果。。。望加分啊!!!
对于您得需求,结果如下:
1234,1235,1236,1243,1245,1246,1253,1254,1256,1263,1264,1265,1324,1325
1326,1342,1345,1346,1352,1354,1356,1362,1364,1365,1423,1425,1426,1432
1435,1436,1452,1453,1456,1462,1463,1465,1523,1524,1526,1532,1534,1536
1542,1543,1546,1562,1563,1564,1623,1624,1625,1632,1634,1635,1642,1643
1645,1652,1653,1654,2134,2135,2136,2143,2145,2146,2153,2154,2156,2163
2164,2165,2314,2315,2316,2341,2345,2346,2351,2354,2356,2361,2364,2365
2413,2415,2416,2431,2435,2436,2451,2453,2456,2461,2463,2465,2513,2514
2516,2531,2534,2536,2541,2543,2546,2561,2563,2564,2613,2614,2615,2631
2634,2635,2641,2643,2645,2651,2653,2654,3124,3125,3126,3142,3145,3146
3152,3154,3156,3162,3164,3165,3214,3215,3216,3241,3245,3246,3251,3254
3256,3261,3264,3265,3412,3415,3416,3421,3425,3426,3451,3452,3456,3461
3462,3465,3512,3514,3516,3521,3524,3526,3541,3542,3546,3561,3562,3564
3612,3614,3615,3621,3624,3625,3641,3642,3645,3651,3652,3654,4123,4125
4126,4132,4135,4136,4152,4153,4156,4162,4163,4165,4213,4215,4216,4231
4235,4236,4251,4253,4256,4261,4263,4265,4312,4315,4316,4321,4325,4326
4351,4352,4356,4361,4362,4365,4512,4513,4516,4521,4523,4526,4531,4532
4536,4561,4562,4563,4612,4613,4615,4621,4623,4625,4631,4632,4635,4651
4652,4653,5123,5124,5126,5132,5134,5136,5142,5143,5146,5162,5163,5164
5213,5214,5216,5231,5234,5236,5241,5243,5246,5261,5263,5264,5312,5314
5316,5321,5324,5326,5341,5342,5346,5361,5362,5364,5412,5413,5416,5421
5423,5426,5431,5432,5436,5461,5462,5463,5612,5613,5614,5621,5623,5624
5631,5632,5634,5641,5642,5643,6123,6124,6125,6132,6134,6135,6142,6143
6145,6152,6153,6154,6213,6214,6215,6231,6234,6235,6241,6243,6245,6251
6253,6254,6312,6314,6315,6321,6324,6325,6341,6342,6345,6351,6352,6354
6412,6413,6415,6421,6423,6425,6431,6432,6435,6451,6452,6453,6512,6513
6514,6521,6523,6524,6531,6532,6534,6541,6542,6543,
实现代码:
- import java.util.*;
- class PermComStr{
- public static void main(String[] args){
- System.out.println(combinations("123456", 4));
- }
- /*思路分析:
- 每行字符个数都是递增 ,下一行的字符是建立在上一行的基础上得到的
- 即在将第一行字符串长度限定为1,第二行为2....,在第一行数据基础上{a,b,c},创建第二行数据,遍历字符串中所字符,并与第一行数据组合。注意每行字符串长度限制
- 1、先将原始字符串转换成字符数组ch
- 2、将原始字符串每个字符添加到Arraylist<String> list集合中
- 3、遍历list集合用每个元素str去查找是否存在数组ch中的元素,如果ch中的字符c没有被str找到则用str+c作为新集合的值返回;
- 4、遍历新集合重复3步骤
- */
- public static List<String> combinations(String str,int num) {
- List<String> list=new ArrayList<String>();
- char[] ch=str.toCharArray();
- if(num>ch.length)
- num=ch.length;
- for(int i=0;i<num;i++){
- list=getList(list, ch);
- }
- return list;
- }
- public static void combinations(String str) {
- combinations(str,str.length());
- }
-
- public static List<String> getList(List<String> list, char[] ch) {
- if(list.size()==0){
- for(char c:ch)
- list.add(c+"");
- return list;
- }
- List<String> newList=new ArrayList<String>();
- for(String str:list)
- for(char c:ch)
- if(str.indexOf(c)==-1)
- newList.add(str+c);
- return newList;
- }
- }
复制代码 |