Skip to content

Instantly share code, notes, and snippets.

@masakid
Created August 17, 2015 06:08
Show Gist options
  • Save masakid/6b285fb14581ccc22a68 to your computer and use it in GitHub Desktop.
Save masakid/6b285fb14581ccc22a68 to your computer and use it in GitHub Desktop.
フィボナッチ数列の問題
import java.math.BigInteger;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
public class FibonutchTest {
/**
* 与えられた項数までのフィボナッチ数列を返却する
* @param num
* @return
*/
protected static Set<BigInteger> getFibonutchList(Integer num){
fact(num);
return answerList;
}
/**
* 回答リスト
*/
static Set<BigInteger> answerList = new TreeSet<>();
/**
* メモ化のDictionary
*/
static Map<Integer, BigInteger> memoMap = new HashMap<>();
/**
* 再帰処理
* @param n
* @return
*/
private static BigInteger fact(Integer n){
BigInteger m = BigInteger.ZERO;
if(n == 0){
answerList.add(BigInteger.ZERO);
return BigInteger.ZERO;
} else if(n == 1){
answerList.add(BigInteger.ONE);
return BigInteger.ONE;
} else {
if(memoMap.containsKey(n)){
m = memoMap.get(n);
} else {
m = fact(n-1).add(fact(n-2));
answerList.add(m);
memoMap.put(n, m);
}
return m;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment