首页 > 代码库 > 简单递归练习

简单递归练习

import java.util.ArrayList;
import java.util.List;

/**
 * Created by itworker365 on 5/10/2017.
 */
public class EasyDiGui {
    public static void main (String[] args) {
        List<Integer> list = new ArrayList<Integer>();
        list.add(1);
        list.add(2);
        list.add(3);
        list.add(4);
        list.add(5);
        list.add(6);
        System.out.println(recursive(list, list.size() - 1));
    }

    public static int recursive (List<Integer> list, int pos) {
        if (pos >= 2) {
            int sum = list.get(pos) + list.get(pos - 1);
            return sum + recursive(list, pos - 2);
        } else if (pos == 1) {
            return list.get(pos) + list.get(pos - 1);
        } else if (pos == 0) {
            return list.get(pos);
        } else {
            return 0;
        }
    }
}

 

简单递归练习