[Leetcode学习-c++&java]Beautiful Arrangement

problem:

Difficulty: medium

Description:

Give a number N, and then return how many perfect arrays can be formed starting from the array index 1 within 1 ~ N, where:

Each element of a perfect array conforms to: arr[i] can be divisible by i, or i can be divisible by arr[i].

Subject link: https://leetcode.com/problems/beautiful-arrangement/

Input range:

  • 1 <= n <= 15

Enter the case:

Example 1:
Input: n = 2
Output: 2
Explanation: 
The first beautiful arrangement is [1,2]:
    - perm[1] = 1 is divisible by i = 1
    - perm[2] = 2 is divisible by i = 2
The second beautiful arrangement is [2,1]:
    - perm[1] = 2 is divisible by i = 1
    - i = 2 is divisible by perm[2] = 1

Example 2:
Input: n = 1
Output: 1

My code:

One violence (all permutations) can be solved. If you hurry up, you just write mathematical formulas. However, there are things that don’t speak martial arts, such as typing watches. After all, N is within 15.

Java:

class Solution {
    int count = 0;
    public int countArrangement(int n) {
        recurtion(n + 1, new boolean[n + 1], 1, 0);
        return count;
    }

    public void recurtion(int n, boolean[] visited, int index, int cur) {
        if(index == n) {
            count ++;
            return;
        }
        for(int i = 1;i < n;i ++) {
            if(i == cur) continue;
            if((i % index == 0 || index % i == 0) && !visited[i]) {
                visited[i] = true;
                recurtion(n, visited, index + 1, i);
                visited[i] = false;
            }
        }
    }
}

Java play table:

class Solution {
    private static int[] map = new int[]{1, 2, 3, 8, 10, 36, 41, 132, 250, 700, 750, 4010, 4237, 10680, 24679};
    public int countArrangement(int n) {
        return map[n - 1];
    }
}

C++:

class Solution {
public:
	int count = 0;
	int countArrangement(int n) {
		short *visited = new short[n + 1];
		recurtion(n + 1, visited, 1, 0);
		return count;
	}
	void recurtion(int len, short *visited, int index, int cur) {
		if (index == len) {
			count++; return;
		}
		for (int i = 1; i < len; i++) {
			if (i == cur) continue;
			if ((i % index == 0 || index % i == 0) && visited[i]) {
				visited[i] = 0;
				recurtion(len, visited, index + 1, i);
				visited[i] = 1;
			}
		}
	}
};

C++ will not hit the table

Guess you like

Origin blog.csdn.net/qq_28033719/article/details/112172340