21.Beautiful Arrangement

2017-02-19  本文已影响0人  Anaven

Leetcode.526

class Solution {
public:
    int countArrangement(int N) {
        vector<int> nums(N, 0);
        vector<bool> isUsed(N, false);
        int count = 0;
        for (int i = 0; i < N; i++) {
            nums[i] = i + 1;
        }
        countArrangement(isUsed, 0, nums, count);
        return count;
    }
    
    void countArrangement(vector<bool> &isUsed, int pos, vector<int> &nums, int &count) {
        
        if (pos == nums.size()) {
            count++;
            return;;
        }
        
        for (int i = 0; i < nums.size(); i++) {
            if (isUsed[i]) continue;
            bool isNotMatch = !(nums[i] % (pos + 1) == 0) 
                && !(((pos + 1) % nums[i]) == 0);
            if (isNotMatch) {
                continue;
            }
            isUsed[i] = true;
            countArrangement(isUsed, pos + 1, nums, count);
            isUsed[i] = false;
        }
    }
};
上一篇下一篇

猜你喜欢

热点阅读