汽车加油问题

就是。。经典问题么。。

有很多个加油站,汽车最远跑多少公里,问你在哪几个地方加油可以让加油次数最少

每个加油站距离不同

import java.util.LinkedList;
import java.util.List;

public class CarAndGas {

	/**
	 * @param args
	 */
	private static int MAX_DISTANCE = 10;
	private static int[] distance = {8,3,5,2,4,7,3,3,2,4,6,7};
	//private static boolean[] choose = {false,false,false,false,false,false,false,false,false,false,false,false,false};
	public static void main(String[] args) {
		List<Integer> list = needGas(0,0);
		System.out.println(list);
	}
	//position is the next station
	private static List<Integer> needGas(int position,int extra) {
		if(distance[position]+extra>MAX_DISTANCE) {
			//in this case the car can not reach.....
			return null;
		}
		if (position == distance.length-1){
			return new LinkedList<Integer>();
		}
		//if choose current station, the problem is.....
		List<Integer> withGas = needGas(position+1,0);
		withGas.add(position);
		//if choose not to put gas
		List<Integer> noGas = needGas(position+1,distance[position]+extra);
		if (noGas == null ||withGas.size()<noGas.size()) {
			return withGas;
		} else {
			return noGas;
		}
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值