Finding all subsets of a given set of distinct integers recursively












1














Given a set of distinct integers, I want to find all the possible subsets (for [1,2,3], the code should print [1], [1,2], [1,3], [1,2,3], [2], [2,3], [3] (not necessarily in that order).



There are a few solutions (like this one) out there but what I want to do is to re-implement the bellow solution with a new recursion and no for loop by passing around the indexes: (start = 0)



public void forSolution(List<List<Integer>> res, int nums, List<Integer> list, int start) {

for (int i = start; i < nums.length; i++) {
List<Integer> tmp = new ArrayList<>(list);
tmp.add(nums[i]);
res.add(new ArrayList<>(tmp));
forSolution(res, nums, tmp, i + 1);
}
}


I thought I need to pass two integers to the method, one for keeping the record of index and the other one for keeping the start point, but I am having problem on when I need to do the index increment (vs start increment).
Any help would be appreciated.










share|improve this question




















  • 1




    Possible duplicate of Generating power set recursively without any loops
    – Prune
    Nov 12 at 23:16










  • @Prune It's not really a duplicate. Please read the whole post before flagging it.
    – Yar
    Nov 12 at 23:25










  • @Yar It's an exact duplicate (except your input is a list of integers, not a string of characters). The algorithms are exactly the same.
    – melpomene
    Nov 12 at 23:28










  • @Prune I edited the question to emphasis on the difference. Basically I just want to re-implement the for solution by passing around the indexes.
    – Yar
    Nov 13 at 0:01










  • Check method 2 in this link: geeksforgeeks.org/recursive-program-to-generate-power-set
    – Ari
    Nov 13 at 0:08
















1














Given a set of distinct integers, I want to find all the possible subsets (for [1,2,3], the code should print [1], [1,2], [1,3], [1,2,3], [2], [2,3], [3] (not necessarily in that order).



There are a few solutions (like this one) out there but what I want to do is to re-implement the bellow solution with a new recursion and no for loop by passing around the indexes: (start = 0)



public void forSolution(List<List<Integer>> res, int nums, List<Integer> list, int start) {

for (int i = start; i < nums.length; i++) {
List<Integer> tmp = new ArrayList<>(list);
tmp.add(nums[i]);
res.add(new ArrayList<>(tmp));
forSolution(res, nums, tmp, i + 1);
}
}


I thought I need to pass two integers to the method, one for keeping the record of index and the other one for keeping the start point, but I am having problem on when I need to do the index increment (vs start increment).
Any help would be appreciated.










share|improve this question




















  • 1




    Possible duplicate of Generating power set recursively without any loops
    – Prune
    Nov 12 at 23:16










  • @Prune It's not really a duplicate. Please read the whole post before flagging it.
    – Yar
    Nov 12 at 23:25










  • @Yar It's an exact duplicate (except your input is a list of integers, not a string of characters). The algorithms are exactly the same.
    – melpomene
    Nov 12 at 23:28










  • @Prune I edited the question to emphasis on the difference. Basically I just want to re-implement the for solution by passing around the indexes.
    – Yar
    Nov 13 at 0:01










  • Check method 2 in this link: geeksforgeeks.org/recursive-program-to-generate-power-set
    – Ari
    Nov 13 at 0:08














1












1








1


2





Given a set of distinct integers, I want to find all the possible subsets (for [1,2,3], the code should print [1], [1,2], [1,3], [1,2,3], [2], [2,3], [3] (not necessarily in that order).



There are a few solutions (like this one) out there but what I want to do is to re-implement the bellow solution with a new recursion and no for loop by passing around the indexes: (start = 0)



public void forSolution(List<List<Integer>> res, int nums, List<Integer> list, int start) {

for (int i = start; i < nums.length; i++) {
List<Integer> tmp = new ArrayList<>(list);
tmp.add(nums[i]);
res.add(new ArrayList<>(tmp));
forSolution(res, nums, tmp, i + 1);
}
}


I thought I need to pass two integers to the method, one for keeping the record of index and the other one for keeping the start point, but I am having problem on when I need to do the index increment (vs start increment).
Any help would be appreciated.










share|improve this question















Given a set of distinct integers, I want to find all the possible subsets (for [1,2,3], the code should print [1], [1,2], [1,3], [1,2,3], [2], [2,3], [3] (not necessarily in that order).



There are a few solutions (like this one) out there but what I want to do is to re-implement the bellow solution with a new recursion and no for loop by passing around the indexes: (start = 0)



public void forSolution(List<List<Integer>> res, int nums, List<Integer> list, int start) {

for (int i = start; i < nums.length; i++) {
List<Integer> tmp = new ArrayList<>(list);
tmp.add(nums[i]);
res.add(new ArrayList<>(tmp));
forSolution(res, nums, tmp, i + 1);
}
}


I thought I need to pass two integers to the method, one for keeping the record of index and the other one for keeping the start point, but I am having problem on when I need to do the index increment (vs start increment).
Any help would be appreciated.







algorithm recursion






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 12 at 23:59

























asked Nov 12 at 22:27









Yar

3,05012947




3,05012947








  • 1




    Possible duplicate of Generating power set recursively without any loops
    – Prune
    Nov 12 at 23:16










  • @Prune It's not really a duplicate. Please read the whole post before flagging it.
    – Yar
    Nov 12 at 23:25










  • @Yar It's an exact duplicate (except your input is a list of integers, not a string of characters). The algorithms are exactly the same.
    – melpomene
    Nov 12 at 23:28










  • @Prune I edited the question to emphasis on the difference. Basically I just want to re-implement the for solution by passing around the indexes.
    – Yar
    Nov 13 at 0:01










  • Check method 2 in this link: geeksforgeeks.org/recursive-program-to-generate-power-set
    – Ari
    Nov 13 at 0:08














  • 1




    Possible duplicate of Generating power set recursively without any loops
    – Prune
    Nov 12 at 23:16










  • @Prune It's not really a duplicate. Please read the whole post before flagging it.
    – Yar
    Nov 12 at 23:25










  • @Yar It's an exact duplicate (except your input is a list of integers, not a string of characters). The algorithms are exactly the same.
    – melpomene
    Nov 12 at 23:28










  • @Prune I edited the question to emphasis on the difference. Basically I just want to re-implement the for solution by passing around the indexes.
    – Yar
    Nov 13 at 0:01










  • Check method 2 in this link: geeksforgeeks.org/recursive-program-to-generate-power-set
    – Ari
    Nov 13 at 0:08








1




1




Possible duplicate of Generating power set recursively without any loops
– Prune
Nov 12 at 23:16




Possible duplicate of Generating power set recursively without any loops
– Prune
Nov 12 at 23:16












@Prune It's not really a duplicate. Please read the whole post before flagging it.
– Yar
Nov 12 at 23:25




@Prune It's not really a duplicate. Please read the whole post before flagging it.
– Yar
Nov 12 at 23:25












@Yar It's an exact duplicate (except your input is a list of integers, not a string of characters). The algorithms are exactly the same.
– melpomene
Nov 12 at 23:28




@Yar It's an exact duplicate (except your input is a list of integers, not a string of characters). The algorithms are exactly the same.
– melpomene
Nov 12 at 23:28












@Prune I edited the question to emphasis on the difference. Basically I just want to re-implement the for solution by passing around the indexes.
– Yar
Nov 13 at 0:01




@Prune I edited the question to emphasis on the difference. Basically I just want to re-implement the for solution by passing around the indexes.
– Yar
Nov 13 at 0:01












Check method 2 in this link: geeksforgeeks.org/recursive-program-to-generate-power-set
– Ari
Nov 13 at 0:08




Check method 2 in this link: geeksforgeeks.org/recursive-program-to-generate-power-set
– Ari
Nov 13 at 0:08












1 Answer
1






active

oldest

votes


















1














I think the algorithm gets easier if you don't bother with indices.



The basic idea is that for any given sublist, each element of the original list is either included or not included. The list of all possible sublists is simply all possible combinations of including / not including each element.



For a recursive implementation, we can consider two cases:




  1. The input list is empty. The empty list only has a single sublist, which is the empty list itself.


  2. The input list consists of a first element x and a list of remaining elements rest. Here we can call our function recursively to get a list of all sublists of rest. To implement the idea of both including and not including x in our results, we return a list consisting of




    • each element of sublists(rest) with x added at the front, representing all sublists of our original list that contain x, and

    • each element of sublists(rest) as is (without x), representing all sublists of our original list that don't contain x.




For example, if the list is [1, 2, 3], we have x = 1 and rest = [2, 3]. The recursive call sublists(rest) produces [2, 3], [2], [3], . For each of those sublists we




  • prepend x (which is 1), giving [1, 2, 3], [1, 2], [1, 3], [1], and

  • don't prepend x, giving [2, 3], [2], [3], .


Concatenating those parts gives our total result as [1, 2, 3], [1, 2], [1, 3], [1], [2, 3], [2], [3], .



Sample implementation:



use strict;
use warnings;

sub sublists {
if (!@_) {
return ;
}
my $x = shift @_;
my @r = sublists(@_);
return (map [$x, @$_], @r), @r;
}

for my $sublist (sublists 1, 2, 3) {
print "[" . join(", ", @$sublist) . "]n";
}


Output:



[1, 2, 3]
[1, 2]
[1, 3]
[1]
[2, 3]
[2]
[3]






share|improve this answer





















  • Very interesting approach! Thank you @melpomene
    – Yar
    Nov 12 at 23:49












  • You are just hiding the loop in map.
    – n.m.
    Nov 13 at 7:04










  • @n.m. sub mymap { my $f = shift; @_ ? ($f->(shift), mymap($f, @_)) : () } Now I have a recursive map.
    – melpomene
    Nov 13 at 8:46










  • Yes you can rewrite any loop to recursion...
    – n.m.
    Nov 13 at 10:39











Your Answer






StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");

StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});


}
});














draft saved

draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53271000%2ffinding-all-subsets-of-a-given-set-of-distinct-integers-recursively%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes









1














I think the algorithm gets easier if you don't bother with indices.



The basic idea is that for any given sublist, each element of the original list is either included or not included. The list of all possible sublists is simply all possible combinations of including / not including each element.



For a recursive implementation, we can consider two cases:




  1. The input list is empty. The empty list only has a single sublist, which is the empty list itself.


  2. The input list consists of a first element x and a list of remaining elements rest. Here we can call our function recursively to get a list of all sublists of rest. To implement the idea of both including and not including x in our results, we return a list consisting of




    • each element of sublists(rest) with x added at the front, representing all sublists of our original list that contain x, and

    • each element of sublists(rest) as is (without x), representing all sublists of our original list that don't contain x.




For example, if the list is [1, 2, 3], we have x = 1 and rest = [2, 3]. The recursive call sublists(rest) produces [2, 3], [2], [3], . For each of those sublists we




  • prepend x (which is 1), giving [1, 2, 3], [1, 2], [1, 3], [1], and

  • don't prepend x, giving [2, 3], [2], [3], .


Concatenating those parts gives our total result as [1, 2, 3], [1, 2], [1, 3], [1], [2, 3], [2], [3], .



Sample implementation:



use strict;
use warnings;

sub sublists {
if (!@_) {
return ;
}
my $x = shift @_;
my @r = sublists(@_);
return (map [$x, @$_], @r), @r;
}

for my $sublist (sublists 1, 2, 3) {
print "[" . join(", ", @$sublist) . "]n";
}


Output:



[1, 2, 3]
[1, 2]
[1, 3]
[1]
[2, 3]
[2]
[3]






share|improve this answer





















  • Very interesting approach! Thank you @melpomene
    – Yar
    Nov 12 at 23:49












  • You are just hiding the loop in map.
    – n.m.
    Nov 13 at 7:04










  • @n.m. sub mymap { my $f = shift; @_ ? ($f->(shift), mymap($f, @_)) : () } Now I have a recursive map.
    – melpomene
    Nov 13 at 8:46










  • Yes you can rewrite any loop to recursion...
    – n.m.
    Nov 13 at 10:39
















1














I think the algorithm gets easier if you don't bother with indices.



The basic idea is that for any given sublist, each element of the original list is either included or not included. The list of all possible sublists is simply all possible combinations of including / not including each element.



For a recursive implementation, we can consider two cases:




  1. The input list is empty. The empty list only has a single sublist, which is the empty list itself.


  2. The input list consists of a first element x and a list of remaining elements rest. Here we can call our function recursively to get a list of all sublists of rest. To implement the idea of both including and not including x in our results, we return a list consisting of




    • each element of sublists(rest) with x added at the front, representing all sublists of our original list that contain x, and

    • each element of sublists(rest) as is (without x), representing all sublists of our original list that don't contain x.




For example, if the list is [1, 2, 3], we have x = 1 and rest = [2, 3]. The recursive call sublists(rest) produces [2, 3], [2], [3], . For each of those sublists we




  • prepend x (which is 1), giving [1, 2, 3], [1, 2], [1, 3], [1], and

  • don't prepend x, giving [2, 3], [2], [3], .


Concatenating those parts gives our total result as [1, 2, 3], [1, 2], [1, 3], [1], [2, 3], [2], [3], .



Sample implementation:



use strict;
use warnings;

sub sublists {
if (!@_) {
return ;
}
my $x = shift @_;
my @r = sublists(@_);
return (map [$x, @$_], @r), @r;
}

for my $sublist (sublists 1, 2, 3) {
print "[" . join(", ", @$sublist) . "]n";
}


Output:



[1, 2, 3]
[1, 2]
[1, 3]
[1]
[2, 3]
[2]
[3]






share|improve this answer





















  • Very interesting approach! Thank you @melpomene
    – Yar
    Nov 12 at 23:49












  • You are just hiding the loop in map.
    – n.m.
    Nov 13 at 7:04










  • @n.m. sub mymap { my $f = shift; @_ ? ($f->(shift), mymap($f, @_)) : () } Now I have a recursive map.
    – melpomene
    Nov 13 at 8:46










  • Yes you can rewrite any loop to recursion...
    – n.m.
    Nov 13 at 10:39














1












1








1






I think the algorithm gets easier if you don't bother with indices.



The basic idea is that for any given sublist, each element of the original list is either included or not included. The list of all possible sublists is simply all possible combinations of including / not including each element.



For a recursive implementation, we can consider two cases:




  1. The input list is empty. The empty list only has a single sublist, which is the empty list itself.


  2. The input list consists of a first element x and a list of remaining elements rest. Here we can call our function recursively to get a list of all sublists of rest. To implement the idea of both including and not including x in our results, we return a list consisting of




    • each element of sublists(rest) with x added at the front, representing all sublists of our original list that contain x, and

    • each element of sublists(rest) as is (without x), representing all sublists of our original list that don't contain x.




For example, if the list is [1, 2, 3], we have x = 1 and rest = [2, 3]. The recursive call sublists(rest) produces [2, 3], [2], [3], . For each of those sublists we




  • prepend x (which is 1), giving [1, 2, 3], [1, 2], [1, 3], [1], and

  • don't prepend x, giving [2, 3], [2], [3], .


Concatenating those parts gives our total result as [1, 2, 3], [1, 2], [1, 3], [1], [2, 3], [2], [3], .



Sample implementation:



use strict;
use warnings;

sub sublists {
if (!@_) {
return ;
}
my $x = shift @_;
my @r = sublists(@_);
return (map [$x, @$_], @r), @r;
}

for my $sublist (sublists 1, 2, 3) {
print "[" . join(", ", @$sublist) . "]n";
}


Output:



[1, 2, 3]
[1, 2]
[1, 3]
[1]
[2, 3]
[2]
[3]






share|improve this answer












I think the algorithm gets easier if you don't bother with indices.



The basic idea is that for any given sublist, each element of the original list is either included or not included. The list of all possible sublists is simply all possible combinations of including / not including each element.



For a recursive implementation, we can consider two cases:




  1. The input list is empty. The empty list only has a single sublist, which is the empty list itself.


  2. The input list consists of a first element x and a list of remaining elements rest. Here we can call our function recursively to get a list of all sublists of rest. To implement the idea of both including and not including x in our results, we return a list consisting of




    • each element of sublists(rest) with x added at the front, representing all sublists of our original list that contain x, and

    • each element of sublists(rest) as is (without x), representing all sublists of our original list that don't contain x.




For example, if the list is [1, 2, 3], we have x = 1 and rest = [2, 3]. The recursive call sublists(rest) produces [2, 3], [2], [3], . For each of those sublists we




  • prepend x (which is 1), giving [1, 2, 3], [1, 2], [1, 3], [1], and

  • don't prepend x, giving [2, 3], [2], [3], .


Concatenating those parts gives our total result as [1, 2, 3], [1, 2], [1, 3], [1], [2, 3], [2], [3], .



Sample implementation:



use strict;
use warnings;

sub sublists {
if (!@_) {
return ;
}
my $x = shift @_;
my @r = sublists(@_);
return (map [$x, @$_], @r), @r;
}

for my $sublist (sublists 1, 2, 3) {
print "[" . join(", ", @$sublist) . "]n";
}


Output:



[1, 2, 3]
[1, 2]
[1, 3]
[1]
[2, 3]
[2]
[3]







share|improve this answer












share|improve this answer



share|improve this answer










answered Nov 12 at 23:08









melpomene

58.2k54489




58.2k54489












  • Very interesting approach! Thank you @melpomene
    – Yar
    Nov 12 at 23:49












  • You are just hiding the loop in map.
    – n.m.
    Nov 13 at 7:04










  • @n.m. sub mymap { my $f = shift; @_ ? ($f->(shift), mymap($f, @_)) : () } Now I have a recursive map.
    – melpomene
    Nov 13 at 8:46










  • Yes you can rewrite any loop to recursion...
    – n.m.
    Nov 13 at 10:39


















  • Very interesting approach! Thank you @melpomene
    – Yar
    Nov 12 at 23:49












  • You are just hiding the loop in map.
    – n.m.
    Nov 13 at 7:04










  • @n.m. sub mymap { my $f = shift; @_ ? ($f->(shift), mymap($f, @_)) : () } Now I have a recursive map.
    – melpomene
    Nov 13 at 8:46










  • Yes you can rewrite any loop to recursion...
    – n.m.
    Nov 13 at 10:39
















Very interesting approach! Thank you @melpomene
– Yar
Nov 12 at 23:49






Very interesting approach! Thank you @melpomene
– Yar
Nov 12 at 23:49














You are just hiding the loop in map.
– n.m.
Nov 13 at 7:04




You are just hiding the loop in map.
– n.m.
Nov 13 at 7:04












@n.m. sub mymap { my $f = shift; @_ ? ($f->(shift), mymap($f, @_)) : () } Now I have a recursive map.
– melpomene
Nov 13 at 8:46




@n.m. sub mymap { my $f = shift; @_ ? ($f->(shift), mymap($f, @_)) : () } Now I have a recursive map.
– melpomene
Nov 13 at 8:46












Yes you can rewrite any loop to recursion...
– n.m.
Nov 13 at 10:39




Yes you can rewrite any loop to recursion...
– n.m.
Nov 13 at 10:39


















draft saved

draft discarded




















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.





Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


Please pay close attention to the following guidance:


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53271000%2ffinding-all-subsets-of-a-given-set-of-distinct-integers-recursively%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Guess what letter conforming each word

Port of Spain

Run scheduled task as local user group (not BUILTIN)