给定数组a[1,2,3],用a里面的元素来生成一个长度为5的数组,打印出其排列组合 ruby代码: def all_possible_arr arr, length = 5 ret = [] length.times do if ret.empty? ret = arr.map {|i| [i]} else new_ret = [] ret.each do |r| arr.each do |e| new_ret << r.clone.unshift(e) end end ret = new_r
一般用dfs来做 最简单的一种: 17. Letter Combinations of a Phone Number Given a digit string, return all possible letter combinations that the number could represent. A mapping of digit to letters (just like on the telephone buttons) is given below. Input:Digit s
题目一(输出国际象棋棋盘) 分析: 用i控制行,j来控制列,根据i+j的和的变化来控制输出黑方格,还是白方格. 主要代码: for i in range(8): for j in range(8): if (i+j)%2!=0: print(chr(219)*2,end='') else: print(' ',end='') print('') 题目二(排列组合问题) 有1.2.3.4个数字,能组成多少个互不相同且无重复数字的四位数?都是多少? 分析: 我们可以先预测一下,共有2
今天群里有朋友求一个排列组合算法,题目是给定长度,输出所有指定字母的组合. 如指定字母a.b.c.d.e.f,长度为2,则结果应为:aa.ab.ac ... ef.ff. 有朋友给出算法,很有特色: var n = 0; for (int i = 0; i < Math.Pow(26, n); ++i) { int t = i; string str = ""; for (int j = n - 1; j >= 0; --j) { int s = (int)Math.Pow