-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStringPermutation.java
More file actions
105 lines (97 loc) · 2.25 KB
/
Copy pathStringPermutation.java
File metadata and controls
105 lines (97 loc) · 2.25 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
package com.wg.offerAlgorithm;
import java.util.Stack;
/*
* 打印字符串中字符的所有排列
*/
public class StringPermutation {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
String str="abc";
// // permutation(str);
combination(str);
}
public static void permutation(String str){
if(str==null)
return;
char[] c=str.toCharArray();
permutation_(c,0);
}
//打印字符串中字符的所有排列
public static void permutation(char[] c,int begin){
if(begin==c.length-1){
System.out.println(String.valueOf(c));
}
else{
//交换
for(int i=begin;i<c.length;i++){
char temp=c[begin];
c[begin]=c[i];
c[i]=temp;
permutation(c,begin+1);
//将交换后的数组还原
temp=c[begin];
c[begin]=c[i];
c[i]=temp;
}
}
}
//判断当前字符是否在之前的c[0]-c[end]中出现过
public static boolean isExist(int start,int end,char[] c){
for(int i=start;i<end;i++){
if(c[end]==c[i]){
return true;
}
}
return false;
}
//加入去重复
public static void permutation_(char[] c,int begin){
if(begin==c.length-1){
System.out.println(String.valueOf(c));
}
else{
//交换
for(int i=begin;i<c.length;i++){
if(!isExist(begin,i,c)){
char temp=c[begin];
c[begin]=c[i];
c[i]=temp;
permutation_(c,begin+1);
//将交换后的数组还原
temp=c[begin];
c[begin]=c[i];
c[i]=temp;
}
}
}
}
//打印字符串中字符的所有组合(没有考虑重复)
public static void combination(String str){
char[] c=str.toCharArray();
if(c.length==0) return;
Stack<Character>stack = new Stack<Character>();
for(int i=1;i<=c.length;i++){
combination(c,0,i,stack);
}
}
public static void combination(char[] chars,int begin, int number,Stack<Character>stack){
//当begin+number大于数组长度时 不满足条件 不要在向stack中添加删除
if(number>1 && (begin+number)>chars.length) return;
if(number==0){
System.out.println(stack.toString());
return; //从当前方法中退出,返回到该调用方法的语句处,继续执行。
}
if(begin==chars.length)
{
return;
}
System.out.println(begin+" "+number);
stack.push(chars[begin]);
combination(chars,begin+1,number-1,stack);
stack.pop();
combination(chars,begin+1,number,stack);
}
}