[LeetCode] Beautiful Arrangement

Suppose you have N integers from 1 to N. We define a beautiful arrangement as an array that is constructed by these N numbers successfully if one of the following is true for the ith position (1 <= i <= N) in this array:

  1. The number at the ith position is divisible by i.
  2. i is divisible by the number at the ith position.

Now given N, how many beautiful arrangements can you construct?

Example 1:

Input: 2
Output: 2
Explanation: 

The first beautiful arrangement is [1, 2]:
Number at the 1st position (i=1) is 1, and 1 is divisible by i (i=1).
Number at the 2nd position (i=2) is 2, and 2 is divisible by i (i=2).
The second beautiful arrangement is [2, 1]:
Number at the 1st position (i=1) is 2, and 2 is divisible by i (i=1).
Number at the 2nd position (i=2) is 1, and i (i=2) is divisible by 1.

Note:

  1. N is a positive integer and will not exceed 15.

找出优美数列的个数,优美数列的定义是:元素本身可以被其在数组中的索引值+1整除,或者索引值+1可以被该元素本身整除,即是一个优美数列

给定一个数字N,该数组由1~N组成。要求判断该数组的全排列中有多少个优美数组。

暴力算法思路:

1、求解全排列。

2、对全排列中每个数组进行判断,并统计。

但是该思路的代码会超时。但是十分清晰。

class Solution {
public:
    int countArrangement(int N) {
        int ans = 0;
        vector<vector<int>> res;
        vector<int> nums;
        for (int i = 1; i <= N; i++)
            nums.push_back(i);
        permute(res, nums, 0);
        for (int i = 0; i < res.size(); i++) {
            int cnt = 0;
            for (int j = 1; j <= N; j++) {
                if ((res[i][j - 1] % j == 0) || (j % res[i][j - 1] == 0))
                    cnt++;
            }
            if (cnt == N)
                ans++;
        }
        return ans;
    }
    
    void permute(vector<vector<int>>& res, vector<int>& nums, int idx) {
        if (idx >= nums.size()) {
            res.push_back(nums);
            return;
        }
        else {
            for (int i = idx; i < nums.size(); i++) {
                swap(nums[i], nums[idx]);
                permute(res, nums, idx + 1);
                swap(nums[idx], nums[i]);
            }
        }
    }
};
// TLE
TLE

回溯法

class Solution {
public:
    int countArrangement(int N) {
        vector<int> nums;
        for (int i = 1; i <= N; i++) 
            nums.push_back(i);
        return helper(N, nums);
    }
    
    int helper(int n, vector<int>& nums) {
        if (n <= 0)
            return 1;
        int cnt = 0;
        for (int i = 0; i < n; i++) {
            if (n % nums[i] == 0 || nums[i] % n == 0) {
                swap(nums[i], nums[n - 1]);
                cnt += helper(n - 1, nums);
                swap(nums[i], nums[n - 1]);
            }
        }
        return cnt;
    }
};
// 8 ms
原文地址:https://www.cnblogs.com/immjc/p/8343663.html