美文网首页
21.Beautiful Arrangement

21.Beautiful Arrangement

作者: Anaven | 来源:发表于2017-02-19 21:26 被阅读0次

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;
        }
    }
};

相关文章

网友评论

      本文标题:21.Beautiful Arrangement

      本文链接:https://www.haomeiwen.com/subject/yaojwttx.html