#!/usr/bin/tclsh # vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: set output [ ] proc combinationSum { sum sofar want numbers } { upvar #0 output outp # puts "\t$sum | $sofar | $want | $numbers | $output" if { $sum == $want } { lappend outp $sofar return TRUE } else { if { ( $sum < $want ) && ( [ lindex $numbers 0 ] > 0 ) && ( [ llength $numbers ] > 0 ) } { combinationSum \ [ expr $sum + [ lindex $numbers 0 ] ] \ [ concat $sofar [ lindex $numbers 0 ] ] \ $want $numbers combinationSum $sum $sofar $want [ lrange $numbers 1 end ] } return TRUE } } set test_input [ list 2 3 5 ] set test_target 20 set test_output [ combinationSum 0 [] $test_target $test_input ] # puts "> $output" # puts [ llength $output ] foreach l $output { puts $l } #### $ ./11104071-perl.pl 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 3 3 2 2 2 2 2 2 3 5 2 2 2 2 2 5 5 2 2 2 2 3 3 3 3 2 2 2 3 3 3 5 2 2 3 3 5 5 2 3 3 3 3 3 3 2 3 5 5 5 3 3 3 3 3 5 5 5 5 5 #### $ ./11104071-tcl.tcl 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 3 3 2 2 2 2 2 2 3 5 2 2 2 2 2 5 5 2 2 2 2 3 3 3 3 2 2 2 3 3 3 5 2 2 3 3 5 5 2 3 3 3 3 3 3 2 3 5 5 5 3 3 3 3 3 5 5 5 5 5