Problem: Count the number of ways to climb up the staircase and we can modify the number of steps at any time to 1 or 2
Solution: int getCount(int n)
{
int [] dp = new int[n+2];
dp [0] = 0;
dp [1] = 1;
dp [2] = 2;
for (int k = 3; k <= n; k++) {
dp [k] = dp [k-1] + dp [k-2];
}
return dp [n];
}
Problem: Rotate a n x n matrix by 90 degrees:
Solution:
static void matrixRotate(int[][] A, int r0, int c0, int rt, int ct)
{
if (r0 >= rt) return;
if (c0 >= ct) return;
var top = new int[ct-c0+1];
int count = 0;
for (int j = 0; j <= ct-c0; j++){
top[count] = A[0][j];
count++;
}
count--;
for (int j = ct; j >= c0; j--)
A[c0][j] = A[ct-j][0];
for (int i = r0; i <= rt; i++)
A[i][c0] = A[rt][i];
for (int j = c0; j <= ct; j++)
A[rt][j] = A[ct-j][ct];
for (int i = rt; i >= r0; i--) {
A[i][ct] = top[count];
count--;
}
matrixRotate(A, r0+1, c0+1, rt-1, ct-1);
}
// Before:
1 2 3
4 5 6
7 8 9
// After:
7 4 1
8 5 2
9 6 3
// Before
1 2
3 4
// After
3 1
4 2
No comments:
Post a Comment