Fast solution to Subset sum

后端 未结 6 1451
不思量自难忘°
不思量自难忘° 2020-11-27 19:09

Consider this way of solving the Subset sum problem:

def subset_summing_to_zero (activities):
  subsets = {0: []}
  for (activity, cost) in activities.iterit         


        
6条回答
  •  伪装坚强ぢ
    2020-11-27 19:35

    Thought I'd share my Scala solution for the discussed pseudo-polytime algorithm described in wikipedia. It's a slightly modified version: it figures out how many unique subsets there are. This is very much related to a HackerRank problem described at https://www.hackerrank.com/challenges/functional-programming-the-sums-of-powers. Coding style might not be excellent, I'm still learning Scala :) Maybe this is still helpful for someone.

    object Solution extends App {
        var input = "1000\n2"
    
        System.setIn(new ByteArrayInputStream(input.getBytes()))        
    
        println(calculateNumberOfWays(readInt, readInt))
    
        def calculateNumberOfWays(X: Int, N: Int) = {
                val maxValue = Math.pow(X, 1.0/N).toInt
    
                val listOfValues = (1 until maxValue + 1).toList
    
                val listOfPowers = listOfValues.map(value => Math.pow(value, N).toInt)
    
                val lists = (0 until maxValue).toList.foldLeft(List(List(0)): List[List[Int]]) ((newList, i) => 
                        newList :+ (newList.last union (newList.last.map(y => y + listOfPowers.apply(i)).filter(z => z <= X)))
                )
    
                lists.last.count(_ == X)        
    
        }
    }
    

提交回复
热议问题