有两种解法:
1、递归,实质是深度优先遍历,但是报栈溢出错误
2、利用队列实现广度优先遍历,可解
package Recursive;
import java.util.LinkedList;
import java.util.Queue;
public class OneStepTwoStep {
/**
* 问题描述:一个人第一步只能前进一米或者是后退一米11,第二步前进两米或者是后退两米,A地与B地相距n米,从A地走到B地需要几米
* 递归解决
*/
/**
* 递归法
* @param start 起始位置、初始值为0
* @param end 终止位置,初始值为n
* @param k 第一步可以前进k米,后退k米
* @return
*/
public static int oneStep(int start, int end, int k){
if(start == end){
return 0;
}else if(Math.abs(start - end) == k) {
return 1;
}else if((start - end) > k){//这种情况只能后退
return oneStep(start - k , end, k + 1) + 1;
}else if((end - start) > k){
return oneStep(start + k, end, k + 1) + 1;
}else {
int frontStep = oneStep(start + k, end, k + 1);
int backStep = oneStep(start - k, end, k + 1);
return frontStep < backStep ? frontStep + 1 : backStep + 1;
}
}
//广度优先遍历
public static int solve(int n){
Queue<Integer> q = new LinkedList<>();
q.add(0);
int depth = 0;
while(!q.isEmpty()){
int size = q.size();
depth++;
while(size-- > 0){
int curSum = q.poll();
for(int i = -1; i <= 1; i += 2){
int newSum = curSum + depth * i;
if(newSum == n){
return depth;
}
q.add(newSum);
}
}
}
return 0;
}
public static void main(String[] args){
System.out.print(solve(300));
}
}