public class Solution {
//回溯法
//根据回溯的思路,同样,可以对本题的Beautiful排列实现。
//比如,当N为5时,使用回溯算法先是得到(1,2,3,4,5)排列,符合要求,符合要求的排列数count+1,
//接着回溯到第四个位置,在剩下的选择中选5,但发现5不符合要求,然后跳过,不再往后判断。
//同样当得到(1,2,5)这前三个排列时,5已经不符合要求,也不会再往后判断(1,2,5,x,x)。
//这样减少了直接穷举递归方法中很多不需要判断操作,提高了效率。
int count = ; public int CountArrangement(int N)
{
if (N == ) return ;
helper(N, , new int[N + ]);
return count;
} //具体来说,计算Beautiful排列的数量,可把长度为N的排列的位置看成结点,
//建立一个辅助类来记录所遍历结点的位置及在该位置符合要求的值,
//当结点的位置超过N长度则认为完成了一次Beautiful排列。
private void helper(int N, int pos, int[] used)
{
if (pos > N)
{
count++;
return;
} for (int i = ; i <= N; i++)
{
if (used[i] == && (i % pos == || pos % i == ))
{
used[i] = ;
helper(N, pos + , used);
used[i] = ;
}
}
}
}

https://leetcode.com/problems/beautiful-arrangement/#/description

leetcode526的更多相关文章

  1. [Swift]LeetCode526. 优美的排列 | Beautiful Arrangement

    Suppose you have N integers from 1 to N. We define a beautiful arrangement as an array that is const ...

随机推荐

  1. TCP/IP 必知必会的十个问题

    本文整理了一些TCP/IP协议簇中需要必知必会的十大问题,既是面试高频问题,又是程序员必备基础素养. 一.TCP/IP模型 TCP/IP协议模型(Transmission Control Protoc ...

  2. Git详解之八 Git与其他系统

    以下内容转载自:http://www.open-open.com/lib/view/open1328070454218.html Git 与其他系统 世界不是完美的.大多数时候,将所有接触到的项目全部 ...

  3. LARAVEL 路由原理分析

    <?php class App {    protected $routes = [];    protected $responseStatus = '200 OK';    protecte ...

  4. BZOJ2724 蒲公英 【分块】

    BZOJ2724 蒲公英 题目背景 亲爱的哥哥: 你在那个城市里面过得好吗? 我在家里面最近很开心呢.昨天晚上奶奶给我讲了那个叫「绝望」的大坏蛋的故事的说!它把人们的房子和田地搞坏,还有好多小朋友也被 ...

  5. Django mysql 字符集问题

    http://www.cnblogs.com/discuss/articles/1862248.html http://www.cnblogs.com/moinmoin/archive/2011/02 ...

  6. 51nod 1019 逆序数

    在一个排列中,如果一对数的前后位置与大小顺序相反,即前面的数大于后面的数,那么它们就称为一个逆序.一个排列中逆序的总数就称为这个排列的逆序数. 如2 4 3 1中,2 1,4 3,4 1,3 1是逆序 ...

  7. LeetCode Friend Circles

    原题链接在这里:https://leetcode.com/problems/friend-circles/description/ 题目: There are N students in a clas ...

  8. Netflix OSS 和 SpringCloud Netflix简介

    Netflix OSS Netflix是一家互联网流媒体播放商,是美国视频巨头,随着Netflix转型为一家云计算公司,它也开始积极参与开源项目. Netflix OSS(Open Source)就是 ...

  9. 安装sphinx报错(undefined reference to `libiconv_open' 、undefined reference to `libiconv'、undefined reference to `libiconv_close'、make[1]: *** No rule to make target `all'. Stop. 、make: *** [all-recursive

    (为知笔记copy过来格式有变,希望对遇到此问题的童鞋有帮助) 具体错误: Thank you for choosing Sphinx! [root@vm-vagrant csft-4.1]# mak ...

  10. php 必须了解提升的知识

    https://blog.csdn.net/m18513057343/article/details/78974292