526. Beautiful Arrangement
来源:互联网 发布:天津软件协会网站 编辑:程序博客网 时间:2024/06/04 01:15
1.题目
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.
2.分析
这道题,思路一般很容易想到就是使用回溯法,而我从常规思路来思考,结果想了好久,以下解法代码简介,思路比较巧妙。
3.解题
class Solution {int count = 0;public int countArrangement(int N) { if(N==0){ return count; } helper(N,1,new int[N+1]); return count;}public void helper(int n, int pos, int[]number){ if(pos>n){ count++; return; } for(int i=1;i<=n;i++){ if(number[i]==0&&(i%pos==0||pos%i==0)){ number[i] = 1; helper(n,pos+1,number); number[i] = 0; } }}}
4.总结
如果是一个正常的思路的话,会是一个全排列,然后进行1~n的%,这样时间复杂度比较高,而如果使用回溯法代码简洁,思路也比较清晰,可能有点烧脑。
阅读全文
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
- iptables详解
- Struts2之实现多种日期格式的转换操作
- QueryDsl查询mongodb数据2
- Android Monkey压力测试
- AndroidStudio无源码动态调试apk
- 526. Beautiful Arrangement
- Java Thread类的interrupted和isInterrupted的区别
- 常用几种人脸对齐算法ASM/AAM/CLM/SDM
- VisualStudio2017 安装失败! 网传的方法无效
- enum
- 什么是MVC模式?
- BidQuoteObserver
- Elasticsearch 连接查询
- 终端执行python脚本 (for Mac)