leetcode526+求出所有的完美安排,递归回溯

https://leetcode.com/problems/beautiful-arrangement/description/

class Solution {
public:
    void helper(int N, vector& visited, int pos, int& res)
    {
        if(pos>N){
            res ++;
            return;
        }
        for(int i=1; i<=N; i++){
            if(visited[i]==0&&(i%pos==0 || pos%i==0)){
                visited[i] = 1;
                helper(N, visited, pos+1, res);
                visited[i] = 0;
            }
        }
    }
    int countArrangement(int N) {
        int res = 0;
        vector visited(N+1, 0);
        helper(N, visited, 1, res);
        return res;
    }
};

 

你可能感兴趣的:(Leetcode)