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:
- The number at the ith position is divisible by i.
- 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:
- 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
- LeetCode 526. Beautiful Arrangement
- 526. Beautiful Arrangement
- 526. Beautiful Arrangement -Medium
- 【Leetcode】526. Beautiful Arrangement
- 526. Beautiful Arrangement
- [LeetCode]526. Beautiful Arrangement
- 【LeetCode】526. Beautiful Arrangement
- leetcode 526. Beautiful Arrangement
- 526. Beautiful Arrangement
- 526. Beautiful Arrangement
- 526. Beautiful Arrangement
- 526. Beautiful Arrangement
- 526. Beautiful Arrangement
- Leetcode: 526. Beautiful Arrangement
- [LeetCode] 526. Beautiful Arrangement
- [LeetCode]526. Beautiful Arrangement
- [LeetCode] 526. Beautiful Arrangement
- LeetCode:526. Beautiful Arrangement
- UVa10012箱子得有多大
- 166.n1-事件分发,让父类不要拦截
- PYTHON解释
- 科研的一些感想
- python的基础知识(1)
- 526. Beautiful Arrangement
- 为 Vue 编写一个插件
- 《java多线程编程技术核心》读书笔记5
- ESP_8266芯片配网方式
- UVa苏丹的继承者
- python time总结
- 用c语言实现一个通讯录; 通讯录可以存储1000个人的信息,信息包括姓名、性别、年龄、电话、住址 提供方法: 1.添加联系人信息 2.删除指定联系人信息 3.查找指定联系人信息 4.修改指定联系&
- Hibernate_部门查询
- <javaScript> 数组去重的方法总结(2017年)