Java 30 lines solution


  • 0
    R
    public class Solution {
        int res = 0;
        int totalres = 0;
        public int numberOfPatterns(int m, int n) {
        	boolean[] visit = new boolean[9];
            helper(m, n, 1, visit, 1);
            helper(m, n, 1, visit, 2);
            totalres += res * 4;
            res = 0;
            helper(m, n, 1, visit, 5);
            totalres += res;
    
            return totalres;
        }
        
        public void helper(int m, int n, int step, boolean[] visit, int pre) {
            if(step == n) {res++; return;}
            if(step >= m) res++;
            
            visit[pre-1] = true;
            for(int i = 1; i<=9; i++) {
                if(!visit[i-1]) {
                    if(! ((i!=5 && i%2==1 && pre!=5 && pre%2==1 && !visit[(i+pre)/2-1]) || (i%2==0 && pre%2==0 && i+pre==10 && !visit[4]))) {
                        helper(m, n, step+1, visit, i);
                    }
                }
            }
            visit[pre-1] = false;
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.