LC 526. Beautiful Arrangement

uppose 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.

Runtime: 168 ms, faster than 18.79% of C++ online submissions for Beautiful Arrangement.

自己的解法就是暴力搜索。

#include <vector>
#include <set>
#include <iostream>
using namespace std;
class Solution {
public:
  int countArrangement(int N) {
    vector<bool> visited(N,false);
    int ret = 0;
    helper(visited, ret, 0);
    return ret;
  }
  void helper(vector<bool>& visited, int& ret, int idx){
    if(idx == visited.size()){
      ret++;
      return;
    }
    for(int i=0; i < visited.size(); i++){
      if(!visited[i] && ((i+1) % (idx+1) == 0 || (idx+1) % (i+1) == 0)){
        visited[i] = true;
        helper(visited, ret, idx+1);
        visited[i] = false;
      }
    }
  }
};

 

看一个比较巧妙的,把每一个数和最后一个index对比,如果满足条件,就把n-1的情况加到结果中,因为这相当于在n-1的结果中加入了后一项,长度增加1,但是数量还是n-1的数量,所以可以直接加

到结果中,但是这里的helper需要带nums,因为交换以后的nums不是1-n了。

class Solution {
//generate all permutaitons swapping from the back and check if valid
private:
    int helper(int n, vector<int>& nums){ //checking index == n
        if (n <= 0){ //a single num is always valid
            return 1;
        }
        int res = 0;
        for (int i = n-1; i >= 0; i--){
            if (nums[i] % n == 0 || n % nums[i] == 0){
                swap(nums[i], nums[n-1]);
                res += helper(n-1, nums);
                swap(nums[i], nums[n-1]);
            }
        }
        return res;
    }
public:
    int countArrangement(int N) {
        vector<int> nums;
        for (int i = 1; i <= N; i++){
            nums.push_back(i);
        }
        return helper(N, nums);
    }
};

 

posted @ 2018-12-28 15:18  yuxihong  阅读(179)  评论(0编辑  收藏  举报