Biểu thức Zero (thuật toán Quay lui BackTracking)

package Advance;

import java.io.FileInputStream;
import java.util.Scanner;

public class BieuThucZero {
public static void main(String[] args) throws Exception {
new BieuThucZero().inIt();
}

int N, Result;
int key[];
int k, t;
String bieuthuc;

private void inIt() throws Exception {
Scanner sc = new Scanner(System.in);
int T;
T = sc.nextInt();
for (int test_case = 1; test_case <= T; test_case++) {
N = sc.nextInt();
key = new int[N - 1];
Result = 0;
backtrack(0);
System.out.println("#"+test_case + " " + Result);
}
}

private void backtrack(int num) {
if (num == N - 1) {
if (checkEnd() == 0) {
Result++;
}
return;
}
for (int i = 0; i < 3; i++) {
key[num] = i;
backtrack(num + 1);
}
}

private int checkEnd() {
bieuthuc = getString();
k = t = 0;
int[] num = new int[N];
int op[] = new int[N - 1];
for (int i = 0; i < bieuthuc.length(); i++) {
if (isOperand(bieuthuc.charAt(i))) {
num[k] = num[k] * 10 + (bieuthuc.charAt(i) - '0');
} else {
if (bieuthuc.charAt(i) == '+') {
op[t] = 1;
} else {
op[t] = 2;
}
t++;
k++;
num[k] = 0;
}
}
int kq = num[0];
for (int i = 0; i < t; i++) {
if (op[i] == 1) {
kq += num[i+1];
} else {
kq -= num[i+1];
}
}
return kq;
}

public boolean isOperand(char x) {
if (x - 48 >= 0 && x - 48 <= 9)
return true;
else
return false;
}

private String getString() {
String s = "";
s += 1;
for (int i = 0; i < N - 1; i++) {
if (key[i] == 0) {
s = s + (i + 2);
}
if (key[i] == 1) {
s += '+';
s = s + (i + 2);
}
if (key[i] == 2) {
s += '-';
s = s + (i + 2);
}
}
return s;
}
}

Nhận xét

Bài đăng phổ biến từ blog này

Nâng cấp máy tính (Thuật toán quay lui)

Tấn công thành trì (Thuật toán Prim tìm cây khung lớn nhất)

Battle City (Thuật toán BFS)