Leetcode - 526. Beautiful Arrangement

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.


question


解法:backtracking

逻辑:

假设我们有个N长的array,我们在array的第一位测试数字1能不能满足条件,如果能满足,我们去到array的下一个位置,测试数字2能不能fit,当1~N全部测试完之后,根据backtraking的特性回弹回:


for i in range(N):

    if the i satisfy requirement , put i on current posistion

    then we call recusion to the 

    foo(currentposn+1,arr)

    free the arr[i] for the future use 


reference:

https://discuss.leetcode.com/topic/79916/java-solution-backtracking/2



最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,788评论 0 33
  • 九九重阳节,登高望远,和一帆一同前往梧桐山,鹏城第一峰。两个小时上山,两个小时下山,也是很累,但尽兴,开心。 下午...
    聂一一阅读 218评论 0 0
  • 2012年10月26日 每天都要兢兢业业地工作,充实的生活!日子在平淡中一天天逝去,青春的脚步好匆忙!我要健身...
    陌上花开ing阅读 100评论 0 0