1.砝码称重(java)
CSDN上已经有人写出来过,想写一下思路
//方法2:DFS搜索
package com.liu.ex1;
import java.util.ArrayList;
import java.util.Scanner;
public class Main1 {
public static int[] value = {1,3,9,27,81};
public static int n = 0;
public static ArrayList result = new ArrayList();
public int getSum() {
int sum = 0;
for(int i = 0;i < result.size();i++)
sum += result.get(i);
return sum;
}
public void dfs(int step) {
if(step == 5) {
if(getSum() == n) {
int i = result.size() - 1;
for(;i >= 0;i--) {
if(result.get(i) != 0) {
System.out.print(result.get(i));
i--;
break;
}
}
for(;i >= 0;i--) {
if(result.get(i) == 0)
continue;
if(result.get(i) > 0)
System.out.print("+");
System.out.print(result.get(i));
}
}
} else {
for(int i = -1;i <= 1;i++) {
int a = i * value[step];
result.add(a);
dfs(step + 1);
result.remove(result.size() - 1);
}
}
}
public static void main(String[] args) {
Main1 test = new Main1();
Scanner in = new Scanner(System.in);
n = in.nextInt();
test.dfs(0);
}
}