Skip to content
This repository has been archived by the owner on Nov 7, 2020. It is now read-only.

Add answers for permutation: fibonacci and parentheses #102

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 42 additions & 0 deletions app/recursion.js
Original file line number Diff line number Diff line change
Expand Up @@ -72,5 +72,47 @@ exports.recursionAnswers = {
temp.slice()
);
}
},

fibonacci: function(n) {
if (n <= 0) {
return 0;
}
if (n === 1 || n === 2) {
return 1;
}
return this.fibonacci(n-1) + this.fibonacci(n-2);
},

validParentheses: function(n) {
if (n < 1) {
return [];
} else if (n === 1) {
return ['()'];
} else {
// use a map instead of an array to prevent duplicates
// e.g.: '()'+'()()' === '()()'+'()'
var comboMap = {};
var innerCombos = this.validParentheses(n-1);

// For each inner combo, add one more pair of parentheses to it
// in each of the 3 valid configurations
for (var i=0; i<innerCombos.length; i++) {
var curInnerCombo = innerCombos[i];

comboMap['(' + curInnerCombo + ')'] = true;
comboMap['()' + curInnerCombo] = true;
comboMap[curInnerCombo + '()'] = true;
}

var comboList = [];
for (var combo in comboMap) {
if (comboMap.hasOwnProperty(combo)) {
comboList.push(combo);
}
}
return comboList;
}
}

};