Leetcode (526) Beautiful Arrangement

beautiful arrangement

backtracking

for each position check each number. set number to one position

class Solution {
    //try n factorial numbers
    int tag[];
    int res= 0;
    public int countArrangement(int N) {
        tag = new int[N+1];
        backtracking(1,N);
        return res;
    }
    void check(int pos, int N){
        if(pos>N) res++;
    }
    void backtracking(int pos, int N){
        
        for(int i = 1; i<=N; i++){
            if(tag[i] == 0 && (pos%i==0 || i%pos==0) ){
                tag[i] = 1; // used number 
                check(pos+1, N);
                backtracking(pos+1, N);
                tag[i] = 0;
            }
        } 
    }
}

 

posted @ 2018-05-13 11:11  wz30  阅读(133)  评论(0编辑  收藏  举报