package com.yx;
import java.util.Stack;
public class TianPing {
Integer[] fama;
int weight;
Stack<Integer> stack=new Stack<Integer>();
StringBuffer sb = new StringBuffer();
public TianPing(Integer[] array,int weight){
this.fama = array;
this.weight = weight;
for(int a:fama){
if(a <= weight){
stack.push(a);
}
}
action(weight,sb);
System.out.println(sb.toString());
}
public void action(int weight,StringBuffer sb){
int totalWeight = 0;
while(weight <= stack.peek()){
if(weight==stack.peek()){
sb.append(stack.peek());
return;
}
stack.pop();
}
for(int i=0;i<stack.size();i++){
totalWeight+=stack.elementAt(i);
}
if(weight>totalWeight){
if(fama[stack.size()]>weight){
sb.append(fama[stack.size()]+"-(");
action(fama[stack.size()]-weight,sb);
sb.append(")");
}
else if(fama[stack.size()]<weight){
sb.append(fama[stack.size()]+"+");
action(weight - fama[stack.size()],sb);
}
}
else if(weight < totalWeight){
stack.pop();
action(weight,sb);
}
else if(weight == totalWeight){
while(!stack.isEmpty()){
sb.append(stack.pop()+"+");
}
sb.setLength(sb.length()-1);
return;
}
}
public static void main(String args[]){
Integer []array = {1,3,9,27,81};
for(int i=1;i<=121;i++){
new TianPing(array,i);
}
}
}
这是我借鉴的了,来个大神给个3进制的算法 |