AcWing 129. 【java】火车进栈
原题链接
简单
作者:
tt2767
,
2019-12-04 00:41:05
,
所有人可见
,
阅读 1039
import java.util.*;
public class Main{
void run(){
int n = jin.nextInt();
dfs2(0, n);
}
// 直接求排列是不对的,不能隔数逆序
void dfs(int status, int n){
if (cnt == 20){
return;
}
else if (status == (1 << n) - 1){
System.out.println(buffer);
cnt += 1;
} else {
for (int i = 0 ; i < n ; i++){
if ((status >> i & 1) == 0){
buffer.add(i+1);
dfs(status | (1 << i), n);
buffer.remove(buffer.size()-1);
}
}
}
}
// 暴力的求法,开始写错了2点,首先应该是并列的if而不是else if;然后List 不能用 StringBuffer代替
void dfs2(int status, int n){
if (cnt == 20){
return;
}
if (buffer.size() == n){
buffer.forEach(x->System.out.print(x));
System.out.println();
cnt += 1;
}
if (!stack.isEmpty()){
int x = stack.peek();
buffer.add(x+1);
stack.pop();
dfs2(status, n);
stack.push(x);
buffer.remove(buffer.size()-1);
}
if (status < n){
stack.push(status);
dfs2(status + 1 , n);
stack.pop();
}
}
private Stack<Integer> stack = new Stack<>();
private List buffer = new ArrayList();
private int cnt = 0;
private Scanner jin = new Scanner(System.in);
public static void main(String[] args) throws Exception{new Main().run();}
}