Listing all permutations of a string/integer

后端 未结 29 1967
没有蜡笔的小新
没有蜡笔的小新 2020-11-22 00:44

A common task in programming interviews (not from my experience of interviews though) is to take a string or an integer and list every possible permutation.

Is there

29条回答
  •  隐瞒了意图╮
    2020-11-22 01:25

    Here's my solution in JavaScript (NodeJS). The main idea is that we take one element at a time, "remove it" from the string, vary the rest of the characters, and insert the element at the front.

    function perms (string) {
      if (string.length == 0) {
        return [];
      }
      if (string.length == 1) {
        return [string];
      }
      var list = [];
      for(var i = 0; i < string.length; i++) {
        var invariant = string[i];
        var rest = string.substr(0, i) + string.substr(i + 1);
        var newPerms = perms(rest);
        for (var j = 0; j < newPerms.length; j++) {
          list.push(invariant + newPerms[j]);
        }
      }
      return list;
    }
    
    module.exports = perms;
    

    And here are the tests:

    require('should');
    var permutations = require('../src/perms');
    
    describe('permutations', function () {
      it('should permute ""', function () {
        permutations('').should.eql([]);
      })
    
      it('should permute "1"', function () {
        permutations('1').should.eql(['1']);
      })
    
      it('should permute "12"', function () {
        permutations('12').should.eql(['12', '21']);
      })
    
      it('should permute "123"', function () {
        var expected = ['123', '132', '321', '213', '231', '312'];
        var actual = permutations('123');
        expected.forEach(function (e) {
          actual.should.containEql(e);
        })
      })
    
      it('should permute "1234"', function () {
        // Wolfram Alpha FTW!
        var expected = ['1234', '1243', '1324', '1342', '1423', '1432', '2134', '2143', '2314', '2341', '2413', '2431', '3124', '3142', '3214', '3241', '3412', '3421', '4123', '4132'];
        var actual = permutations('1234');
        expected.forEach(function (e) {
          actual.should.containEql(e);
        })
      })
    })
    

提交回复
热议问题