如对[1,2,3],将得到[123,132,213,231,312,321]
结果数字不重复。
思路:
x([1,2,3])  ->
 y(1,x([2,3])) + y(2,x([1,3])) + y(3,x([1,2]))

y(1,x[2,3]) ->
[12,13]

代码:

arr = [1,2,3]

def y(num,arr)
  arr.collect{|it| num.to_s + it.to_s }
end

def x(arr)
  return arr.dup if arr.size==1
  result = []
  arr.each_index do |i|
    arr1 = arr.dup
    num = arr1.delete_at(i)
    result.concat(y(num,x(arr1)))
  end
  return result
end

def z(arr)
  arr.uniq.collect{|it| it.to_i}
end

require ‘pp’
pp z(x(arr))


1条评论

  1. 偶来一个js版的吧

    function permutation(arrays) {

    if(arrays.length <= 1) return [arrays];

    var ret = [];

    eachof(function(x) {

    return map(function(p) {

    ret.push([x,p]);

    }, permutation(filter(function(item) {

    return x != item;

    }, arrays)))

    },

    arrays);

    return ret;

    };

发表评论

评论也有版权!