Number of ways 类
public class Solution {
public int numberOfPatterns(int m, int n) {
int[][] passThrough = new int[10][10];
boolean[] visited = new boolean[10];
// Rows
passThrough[1][3] = passThrough[3][1] = 2;
passThrough[4][6] = passThrough[6][4] = 5;
passThrough[7][9] = passThrough[9][7] = 8;
// Cols
passThrough[1][7] = passThrough[7][1] = 4;
passThrough[2][8] = passThrough[8][2] = 5;
passThrough[3][9] = passThrough[9][3] = 6;
// Diagnals
passThrough[1][9] = passThrough[9][1] = 5;
passThrough[3][7] = passThrough[7][3] = 5;
int count = 0;
for(int i = m; i <= n; i++){
count += 4*dfs(visited, passThrough, 1, i - 1) +
4*dfs(visited, passThrough, 2, i - 1) +
dfs(visited, passThrough, 5, i - 1);
}
return count;
}
// take currently considering element
private int dfs(boolean[] visited, int[][] passThrough, int curNum, int lenRemain){
if(lenRemain < 0) return 0;
if(lenRemain == 0) return 1;
int count = 0;
visited[curNum] = true;
for(int i = 1; i <= 9; i++){
if(!visited[i] && (passThrough[curNum][i] == 0 || visited[passThrough[curNum][i]])){
count += dfs(visited, passThrough, i, lenRemain - 1);
}
}
visited[curNum] = false;
return count;
}
}注意这里内外循环的顺序不能错,要先按 sum 从小到大的顺序看,然后才是遍历每个元素。因为所谓 bottom-up,是相对于 sum 而言的,不是相对于已有元素的 index 而言的。
特殊 case : 11,101,110, 501..
从左向右:

从右向左:
Last updated