526 Beautiful Arrangement

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

C++:

class Solution {
public:
    int countArrangement(int N)
    {
        int res = 0;
        vector<int> visited(N + 1, 0);
        helper(N, visited, 1, res);
        return res;
    }
    void helper(int N, vector<int>& 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;
            }
        }
    }
};

 参考:http://www.cnblogs.com/grandyang/p/6533276.html

posted on 2018-04-22 20:36  lina2014  阅读(85)  评论(0编辑  收藏  举报

导航