526. Beautiful Arrangement

来源:互联网 发布:软件界面显示不全 编辑:程序博客网 时间:2024/06/03 07:07

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: 2Output: 2Explanation: 
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、递归的条件是:num%i==0 || i %num==0

2、helper需要的参数:可以存integer的list,记录当前数有没有被用过的boolean类型数组used,计数用的count,目标值n

代码如下:

public class Solution {    int count;        public int countArrangement(int N) {        count = 0;        helper(new ArrayList<Integer>(), new boolean[N + 1], N);        return count;    }        private void helper(List<Integer> list, boolean[] used, int n) {        if (list.size() == n) {            count ++;        }        for (int i = 1; i <= n; i ++) {            if (!used[i]) {                int id = list.size() + 1;                if (id % i == 0 || i % id == 0) {                    list.add(i);                    used[i] = true;                    helper(list, used, n);                    list.remove(list.size() - 1);                    used[i] = false;                }            }        }    }}
上面的代码相当于从第一位,一直放到最高位,这道题只是计数,没让保存,可以把list替换成一个index,代码稍微改变一下。代码如下:

public class Solution {    public int countArrangement(int N) {        boolean[] arr = new boolean[N+1];        return find(arr, N);    }        private int find(boolean[] arr, int idx){        if(idx==0){ return 1; }                int res = 0;        for(int i=1; i<arr.length; i++){            if(!arr[i] && (idx%i==0 || i%idx==0)){                arr[i] = true;                res += find(arr, idx-1);                arr[i] = false;            }        }        return res;    }}

0 0
原创粉丝点击