-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRecursion
More file actions
80 lines (64 loc) · 2.06 KB
/
Recursion
File metadata and controls
80 lines (64 loc) · 2.06 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Set;
import java.util.Stack;
public class Recursion {
//ex2 - prints to the screen all the combinations of 1 and 2 that sums up to the value inserted.
public static void options(int n)
{
int[] history = new int[n];
options(n,history,0);
}
private static void options(int n, int[] history,int i)
{
if(n==0)
{
printHistory(history,0, i);
System.out.println("\n" + i + "\n");
System.out.println();
}
if(n>0)
{
history[i] = 1;
options(n-1,history,i+1);
history[i] = 2;
options(n-2,history,i+1);
}
}
public static void printHistory(int[] history,int from,int to) {
if (from < to) {
System.out.print(history[from] + "\t");
printHistory(history, from + 1, to);
}
}
//return all permutation
public static void
permutations(Set<Integer> items, Stack<Integer> permutation, int size) {
/* permutation stack has become equal to size that we require */
if(permutation.size() == size) {
/* print the permutation */
System.out.println(Arrays.toString(permutation.toArray(new Integer[0])));
}
/* items available for permutation */
Integer[] availableItems = items.toArray(new Integer[0]);
for(Integer i : availableItems) {
/* add current item */
permutation.push(i);
/* remove item from available item set */
items.remove(i);
/* pass it on for next permutation */
permutations(items, permutation, size);
/* pop and put the removed item back */
items.add(permutation.pop());
}
}
//fibonacci without DP
public static int simpleFibonacci(int n) {
int res=0;
if(n==1 || n==2)
res = 1;
else
res = simpleFibonacci(n-1) + simpleFibonacci(n-2);
return res;
}
}